luxid-orm 0.1.1

The Lucid data layer for the Luxid web framework
Documentation
//! Model lifecycle hooks.
//!
//! Hooks are declared on the derive rather than as `#[before_save]` attributes
//! inside `#[luxid::model]`, and that is a deliberate trade.
//!
//! `luxid::insert` and `luxid::update` *require* this trait, so hooks always
//! run on the ordinary write path — a hook that silently fails to fire is a
//! security bug, not an inconvenience (an unhashed password reaches the
//! database). Requiring the trait means every model must implement it, which
//! means the derive must generate it, which means the derive must know which
//! hooks exist. Declaring them anywhere else would either leave models without
//! hooks uninsertable or produce conflicting impls.
//!
//! The cost is that a hook's name appears in the attribute as well as on its
//! function. The benefit is that there is no way to write a model whose hooks
//! quietly do not run.

use luxid_core::error::Result;
use luxid_core::middleware::BoxFuture;
use sea_orm::ActiveModelTrait;

use crate::model::Lucid;

/// Lifecycle callbacks, generated by `#[derive(Model)]`.
///
/// Order on create: `before_save` → `before_create` → write → `after_create` →
/// `after_save`. Update mirrors it. An `Err` from any *before* hook aborts the
/// write.
pub trait Hooks: Lucid {
    /// The entity's `ActiveModel`.
    type Active: ActiveModelTrait;

    /// Runs before every write, create or update.
    fn before_save(active: &mut Self::Active) -> BoxFuture<'_, Result<()>> {
        let _ = active;
        Box::pin(async { Ok(()) })
    }

    fn before_create(active: &mut Self::Active) -> BoxFuture<'_, Result<()>> {
        let _ = active;
        Box::pin(async { Ok(()) })
    }

    fn before_update(active: &mut Self::Active) -> BoxFuture<'_, Result<()>> {
        let _ = active;
        Box::pin(async { Ok(()) })
    }

    /// Runs after the row is written and reloaded.
    ///
    /// An `Err` here propagates to the caller, but the row is already written —
    /// wrap the call in a transaction if that matters.
    fn after_create(model: &Self) -> BoxFuture<'_, Result<()>> {
        let _ = model;
        Box::pin(async { Ok(()) })
    }

    fn after_update(model: &Self) -> BoxFuture<'_, Result<()>> {
        let _ = model;
        Box::pin(async { Ok(()) })
    }

    fn after_save(model: &Self) -> BoxFuture<'_, Result<()>> {
        let _ = model;
        Box::pin(async { Ok(()) })
    }
}