floz_orm/hooks.rs
1//! Lifecycle hooks for floz models.
2//!
3//! The `FlozHooks` trait provides `before_*` and `after_*` callbacks for
4//! create, save, and delete operations. All methods have default no-op
5//! implementations — override only the ones you need.
6//!
7//! # Usage
8//!
9//! By default, the `schema!` macro generates `impl FlozHooks for Model {}`
10//! (using all defaults). To provide custom hooks, annotate the model with
11//! `#[hooks]` and implement the trait yourself:
12//!
13//! ```ignore
14//! floz::schema! {
15//! #[hooks]
16//! model User("users") {
17//! id: integer("id").auto_increment().primary(),
18//! name: varchar("name", 100),
19//! updated_at: datetime("updated_at").tz(),
20//! }
21//! }
22//!
23//! impl floz::FlozHooks for User {
24//! fn before_save(&mut self) -> Result<(), floz::FlozError> {
25//! self.set_updated_at(chrono::Utc::now());
26//! Ok(())
27//! }
28//! }
29//! ```
30
31use crate::error::FlozError;
32
33/// Lifecycle hooks for database operations.
34///
35/// `before_*` hooks return `Result` — returning `Err(...)` aborts the operation.
36/// `after_*` hooks are fire-and-forget notifications.
37pub trait FlozHooks: Sized {
38 /// Called before `create()`. Return `Err` to abort the INSERT.
39 ///
40 /// Takes `&self` (immutable). Modify fields before calling `create()`.
41 fn before_create(&self) -> Result<(), FlozError> {
42 Ok(())
43 }
44
45 /// Called after a successful `create()`.
46 fn after_create(&self) {}
47
48 /// Called before `save()`. Can modify the entity (e.g., set `updated_at`).
49 /// Return `Err` to abort the UPDATE.
50 ///
51 /// If this hook sets a field via `set_*()`, the field becomes dirty and
52 /// will be included in the UPDATE statement.
53 fn before_save(&mut self) -> Result<(), FlozError> {
54 Ok(())
55 }
56
57 /// Called after a successful `save()`.
58 fn after_save(&self) {}
59
60 /// Called before `delete()`. Return `Err` to abort the DELETE.
61 fn before_delete(&self) -> Result<(), FlozError> {
62 Ok(())
63 }
64
65 /// Called after a successful `delete()`.
66 fn after_delete(&self) {}
67}