Skip to main content

autumn_macros_model/
lib.rs

1//! Database-model proc macros for the Autumn web framework.
2//!
3//! This crate provides the database-layer attribute macros:
4//! `#[model]`, `#[commentable]` (consumed by `#[model]`), and `#[service]`.
5//! It is split out of `autumn-macros` so a build that never touches the
6//! database layer never compiles this codegen.
7//!
8//! Users should not depend on this crate directly — use `autumn-web`
9//! instead, which re-exports everything behind its `db` feature.
10
11mod commentable;
12mod model;
13mod service;
14
15use proc_macro::TokenStream;
16
17/// Attribute macro for Autumn database models.
18///
19/// Applies Diesel (`Queryable`, `Selectable`, `Insertable`) and Serde
20/// (`Serialize`, `Deserialize`) derives, plus a `#[diesel(table_name)]`
21/// attribute. The table name can be specified explicitly or inferred
22/// from the struct name by converting `PascalCase` to `snake_case`
23/// and appending `s`.
24///
25/// # Examples
26///
27/// Explicit table name:
28///
29/// ```ignore
30/// use autumn_web::model;
31///
32/// #[model(table = "users")]
33/// pub struct User {
34///     pub id: i64,
35///     pub name: String,
36/// }
37/// ```
38///
39/// Inferred table name (`BlogPost` -> `blog_posts`):
40///
41/// ```ignore
42/// use autumn_web::model;
43///
44/// #[model]
45/// pub struct BlogPost {
46///     pub id: i64,
47///     pub title: String,
48/// }
49/// ```
50///
51/// # Associations
52///
53/// Declare `#[belongs_to]`, `#[has_many]`, and `#[has_one]` on the struct to
54/// get batched eager preloading for free — no hand-written join queries, no
55/// N+1. Foreign keys and accessor names are inferred from the target's type
56/// name, with `fk = ...` / `name = ...` overrides:
57///
58/// ```ignore
59/// #[model]
60/// #[belongs_to(User, fk = author_id)]  // fk on THIS model
61/// #[has_many(Comment)]                 // fk (post_id) on the TARGET
62/// pub struct Post {
63///     #[id]
64///     pub id: i64,
65///     pub author_id: i64,
66///     pub title: String,
67/// }
68/// ```
69///
70/// Preload associations through a repository (`Model::preload()` builds the
71/// spec; `_with` nests into the related model's own associations):
72///
73/// ```ignore
74/// let posts = repo.find_all().await?;
75/// let posts = repo.preload(posts, Post::preload().author().comments()).await?;
76/// for post in &posts {
77///     let author = post.author()?;      // Result<Option<&Preloaded<User>>, NotLoaded>
78///     let comments = post.comments()?;  // Result<&[Preloaded<Comment>], NotLoaded>
79/// }
80/// ```
81///
82/// An association that was not preloaded returns `NotLoaded` from its
83/// accessor rather than issuing SQL — autumn never lazy-loads.
84///
85/// ## Many-to-many (`through =`)
86///
87/// Add `through = <join_table>` to `#[has_many]` to declare a many-to-many
88/// association backed by a join table, with the same batched preload
89/// semantics as `belongs_to`/`has_many`/`has_one`:
90///
91/// ```ignore
92/// #[model]
93/// #[has_many(Tag, through = post_tags)]  // join columns default to post_id / tag_id
94/// pub struct Post {
95///     #[id]
96///     pub id: i64,
97///     pub title: String,
98/// }
99/// ```
100///
101/// Join columns default to `{source}_id` / `{target}_id` and can be
102/// overridden with `fk = ...` and `target_fk = ...`; the join table itself
103/// needs no hand-written `diesel::table!` — the macro emits one and requires
104/// a composite primary key on `(fk, target_fk)`:
105///
106/// ```sql
107/// CREATE TABLE post_tags (
108///     post_id BIGINT NOT NULL REFERENCES posts(id),
109///     tag_id  BIGINT NOT NULL REFERENCES tags(id),
110///     PRIMARY KEY (post_id, tag_id)
111/// );
112/// ```
113///
114/// `Post::preload().tags()` issues one batched `INNER JOIN` query (plus one
115/// more per level of `_with` nesting) — a fixed number of queries regardless
116/// of how many tags each post has. The generated `tags()` accessor returns
117/// `&[Arc<Preloaded<Tag>>]` (rather than `has_many`'s plain
118/// `&[Preloaded<Tag>]`): the same tag can legitimately be linked to more than
119/// one currently-loaded post, so it's shared via `Arc` instead of being
120/// duplicated per parent.
121///
122/// The association also generates three mutation helpers on the model's
123/// `#[repository]` — `add_{singular}`, `remove_{singular}`, and
124/// `set_{plural}` (replace-all) — each idempotent and requiring no
125/// hand-written SQL:
126///
127/// ```ignore
128/// repo.add_tag(post_id, tag_id).await?;      // idempotent: ON CONFLICT DO NOTHING
129/// repo.remove_tag(post_id, tag_id).await?;   // idempotent: no-op if unlinked
130/// repo.set_tags(post_id, &tag_ids).await?;   // replace-all, one transaction
131/// ```
132///
133/// The `add_`/`remove_` singular is derived from the target *type* name, so a
134/// model may declare at most one m2m association per target type by default —
135/// a second one to the same target would generate colliding helpers (a compile
136/// error). To declare two m2m associations to the same target (e.g. a
137/// self-referential `followers`/`following` pair through one `Friendship` join
138/// table), give each a distinct explicit `helper = "..."` override, which sets
139/// the singular used for its `add_`/`remove_` helpers:
140///
141/// ```ignore
142/// #[model]
143/// #[has_many(User, through = friendships, name = followers,
144///            fk = followed_id, target_fk = follower_id, helper = "follower")]
145/// #[has_many(User, through = friendships, name = following,
146///            fk = follower_id, target_fk = followed_id, helper = "following")]
147/// pub struct User { /* ... */ }
148/// // -> add_follower/remove_follower and add_following/remove_following
149/// ```
150///
151/// # Votable (reactions)
152///
153/// `#[votable(by = <Reactor>)]` declares a reaction association (#1362): a
154/// `(reactor, target)`-unique edge table plus an aggregate column maintained on
155/// this model. It replaces the hand-written toggle/flip/upsert SQL and the
156/// score recompute that every voting, liking or bookmarking feature otherwise
157/// grows.
158///
159/// ```ignore
160/// #[model]
161/// #[votable(by = User, aggregate = sum)]   // signed up/down votes
162/// pub struct Post {
163///     #[id]
164///     pub id: i64,
165///     pub title: String,
166///     pub score: i64,                      // the aggregate column
167/// }
168/// ```
169///
170/// Two modes: `aggregate = sum` (the default — signed values, `score =
171/// SUM(value)`) and `aggregate = count` (unary likes — no value column,
172/// `{name}_count = COUNT(*)`). Every name is inferred and every inference has
173/// an override:
174///
175/// | Key | Default | Meaning |
176/// |---|---|---|
177/// | `by` | **required** | the reactor model, e.g. `User` |
178/// | `aggregate` | `sum` | `sum` \| `count` |
179/// | `name` | `vote` | reaction name; drives `table` and the count column |
180/// | `table` | `pluralize(name)` → `votes` | the edge table |
181/// | `reactor_fk` | `{snake(by)}_id` → `user_id` | edge column → reactor |
182/// | `target_fk` | `{snake(Model)}_id` → `post_id` | edge column → this model |
183/// | `value_column` | `value` (sum only) | the edge's signed value |
184/// | `column` | `score` (sum) / `{name}_count` (count) | aggregate column |
185///
186/// A likes feature is therefore `#[votable(by = User, aggregate = count, name
187/// = like)]` → table `likes`, column `like_count`. At most one `#[votable]` per
188/// model.
189///
190/// `by` may name a hand-written struct — it is name-resolved at compile time
191/// but carries no trait bound, so the reactor's `i64` primary key is
192/// documented contract, not a compile check (the edge table binds the reactor
193/// FK as `BIGINT`; a UUID-keyed reactor fails on first use with a database
194/// type error). The **target** model's `#[id]` and aggregate column *are*
195/// compile-checked as `i64`.
196///
197/// **Write `#[votable]` *below* `#[model]`.** It is consumed by `#[model]`, not
198/// registered as an attribute in its own right, so an attribute macro written
199/// above it never sees it — an error reading `cannot find attribute `votable`
200/// in this scope` means the two lines are the wrong way round.
201///
202/// ## Required migration
203///
204/// The edge table is the user's to create, and its **composite `UNIQUE
205/// (reactor_fk, target_fk)` is load-bearing**: it is the `ON CONFLICT` arbiter
206/// the generated upsert names, and it is what makes "at most one edge per
207/// (reactor, target)" a database guarantee. The value column is `SMALLINT`, the
208/// aggregate column `BIGINT NOT NULL DEFAULT 0`, and the model's own primary key
209/// must be `BIGINT`/`i64` (both edge foreign keys are bound as `i64`; a
210/// UUID-keyed model is a compile error).
211///
212/// `NOT NULL` on both foreign keys is strongly recommended: `NULL`s are
213/// distinct in a unique constraint, so a nullable column is not covered by the
214/// arbiter. A nullable *target* FK is nevertheless tolerated when every row this
215/// association writes is non-`NULL` — the shape an XOR edge table has (reddit-
216/// clone's `votes` points at either a post or a comment), where the unique
217/// constraint still fully covers the non-`NULL` rows `react()` creates.
218///
219/// The `CHECK` on `value` is load-bearing in sum mode: **`react()` does not
220/// validate `value`** — it writes what it is given, and the sum is only
221/// meaningful because the database refuses anything outside the legal set.
222/// Never bind `value` straight from a request; map the request to `1` / `-1`
223/// yourself. A violating value surfaces as a database error (a 500), not a
224/// validation failure.
225///
226/// ```sql
227/// CREATE TABLE votes (
228///     id      BIGSERIAL PRIMARY KEY,
229///     user_id BIGINT NOT NULL REFERENCES users(id),
230///     post_id BIGINT NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
231///     value   SMALLINT NOT NULL CHECK (value IN (-1, 1)),
232///     UNIQUE (user_id, post_id)          -- the ON CONFLICT arbiter
233/// );
234/// ALTER TABLE posts ADD COLUMN score BIGINT NOT NULL DEFAULT 0;
235/// -- aggregate = count: drop the `value` column entirely.
236/// ```
237///
238/// ## Generated helpers
239///
240/// A `{Model}Reactions` trait, blanket-implemented for the model's
241/// `#[repository]`:
242///
243/// ```ignore
244/// use autumn_web::repository::{Reaction, ReactionOutcome};
245///
246/// // sum mode. (count mode: `react(reactor_id, target_id)` — no value.)
247/// let r: Reaction = posts.react(user_id, post_id, 1).await?;
248/// r.value;      // Option<i16>: the reactor's reaction AFTER the call
249/// r.aggregate;  // i64: the newly persisted score, ground truth at commit
250/// r.outcome;    // Inserted | Flipped | Removed
251///
252/// let mine: Option<i16> = posts.reaction_of(user_id, post_id).await?;
253/// ```
254///
255/// `react()` is race-safe: the same value again toggles the edge off, a
256/// different value flips it in place, a new one inserts it — and the aggregate
257/// is recomputed from ground truth (`SUM`/`COUNT`) and persisted in the **same
258/// transaction**, so a reader never observes edge/aggregate disagreement. The
259/// target row is locked (`SELECT ... FOR NO KEY UPDATE` on Postgres — it does
260/// not conflict with the `FOR KEY SHARE` locks foreign-key checks take, so
261/// concurrent inserts referencing the target do not queue behind votes;
262/// `BEGIN IMMEDIATE` on `SQLite`) for the whole read-decide-write-recompute
263/// window, so concurrent reactions on one target converge to at most one edge
264/// per `(reactor, target)` and the persisted aggregate is exact even across
265/// *different* reactors.
266///
267/// It is **not idempotent** — it is a toggle. Retrying a call that timed out can
268/// invert the outcome, because the first attempt may have committed; callers
269/// that need retry safety dedupe above this layer (an idempotency key on the
270/// HTTP request). `reaction_of()` is a plain read: it follows the repository's
271/// read route (so a replica may serve it) and does not pin read-your-writes, so
272/// render from the `Reaction` that `react()` returned rather than re-reading.
273///
274/// When the model has a `deleted_at` field, reacting to a soft-deleted target
275/// is `NotFound` and leaves its aggregate untouched.
276///
277/// Tenant-isolated on the same terms: when the model has a `tenant_id` field
278/// **and** the repository is `#[repository(..., tenant_scoped)]`, both the
279/// target lock and the aggregate `UPDATE` carry `tenant_id = <current
280/// tenant>`, so another tenant's `target_id` is `NotFound` before any write and
281/// `reaction_of()` reports `None` for it. No tenant context is an error (as for
282/// any derived query) and `across_tenants()` opts out. A model without the
283/// column emits none of this. The m2m `add_*` / `remove_*` helpers are not
284/// covered — they remain id-scoped.
285///
286/// `react()` acquires its **own** pooled connection and does not join an
287/// enclosing `Db::tx` — do not hold a `Db` extractor across the call on a small
288/// connection pool.
289#[proc_macro_attribute]
290pub fn model(attr: TokenStream, item: TokenStream) -> TokenStream {
291    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
292        model::model_macro(attr, item)
293    })
294    .into()
295}
296
297/// Define a service for cross-model orchestration and non-DB side effects.
298///
299/// Generates a `XxxServiceImpl` struct with dependency injection via
300/// `FromRequestParts`, so it can be used as a handler parameter just
301/// like repositories.
302///
303/// Use `#[service]` when your logic orchestrates **multiple repositories**
304/// or involves **non-DB side effects** (email, API calls, etc.).
305/// For single-model CRUD and validation, use `#[repository]` instead.
306///
307/// # Examples
308///
309/// ```ignore
310/// use autumn_web::service;
311///
312/// #[service]
313/// pub trait OrderService {
314///     fn deps(order_repo: PgOrderRepository, inventory_repo: PgInventoryRepository);
315///
316///     async fn place_order(&self, req: PlaceOrderRequest) -> AutumnResult<Order>;
317/// }
318///
319/// // You implement the business logic:
320/// impl OrderServiceImpl {
321///     pub async fn place_order(&self, req: PlaceOrderRequest) -> AutumnResult<Order> {
322///         let order = self.order_repo.save(&req.into()).await?;
323///         self.inventory_repo.reserve(order.id).await?;
324///         Ok(order)
325///     }
326/// }
327///
328/// // Then use it in handlers, just like a repository:
329/// #[get("/orders/{id}")]
330/// async fn get_order(svc: OrderServiceImpl) -> AutumnResult<Json<Order>> {
331///     // ...
332/// }
333/// ```
334#[proc_macro_attribute]
335pub fn service(attr: TokenStream, item: TokenStream) -> TokenStream {
336    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
337        service::service_macro(attr, item)
338    })
339    .into()
340}