The Problem
Building a typical CRUD application requires writing the same boilerplate over and over: entity struct, create DTO, update DTO, response DTO, row struct, repository trait, SQL implementation, and 6+ From implementations.
That's 200+ lines of boilerplate for a single entity.
The Solution
Done. The macro generates everything else.
Installation
[]
= { = "0.14", = ["postgres", "api"] }
Feature flags
| Feature | Default | What it does |
|---|---|---|
postgres |
✓ | Generate sqlx::PgPool-backed repository implementations |
events |
✓ | Generate {Entity}Event enum (Created / Updated / Deleted variants) |
commands |
✓ | CQRS command pattern: command structs + dispatcher (#[entity(commands)], #[command(...)]) |
hooks |
✓ | {Entity}Hooks trait with before/after lifecycle methods |
transactions |
✓ | {Entity}TransactionRepo adapter + transaction builder helpers (#[entity(transactions)]) |
aggregate_root |
✓ | New{Entity} constructor type and transactional save() (#[entity(aggregate_root)]) |
migrations |
✓ | Compile-time MIGRATION_UP / MIGRATION_DOWN SQL constants (#[entity(migrations)]) |
projections |
✓ | Projection structs and find_by_id_<projection> lookups (#[projection(...)]) |
clickhouse |
Generate ClickHouse-backed repositories (planned) | |
mongodb |
Generate MongoDB-backed repositories (planned) | |
streams |
{Entity}Subscriber using Postgres LISTEN/NOTIFY (pulls in events) |
|
outbox |
Transactional-outbox enqueue in generated writes + OutboxDrainer runtime (pulls in events) |
|
api |
Generate HTTP handlers (axum) and utoipa OpenAPI schemas |
|
validate |
Wire up validator::Validate on generated DTOs |
|
tracing |
Wrap every generated async method in #[tracing::instrument] carrying entity + op span fields |
Default features cover the full entity-attribute surface so existing projects work without changes. For lean builds, opt out of what you don't need:
[]
# Just repositories — no events, hooks, commands, etc.
= { = "0.14", = false, = ["postgres"] }
If you use an entity attribute whose feature is disabled (e.g. #[entity(commands)] without features = ["commands"]), the macro emits a compile_error! at the attribute pointing to the missing feature.
Enable extras alongside the defaults:
[]
= { = "0.14", = ["postgres", "api", "tracing", "streams"] }
= "0.1"
= "0.3"
Features
| Feature | Description |
|---|---|
| Zero Runtime Cost | All code generation at compile time |
| Type Safe | Change a field once, everything updates |
| Auto HTTP Handlers | api(handlers) generates CRUD endpoints + router |
OpenAPI Docs |
Auto-generated Swagger/OpenAPI documentation |
| Query Filtering | Type-safe #[filter], #[filter(like)], #[filter(range)] |
| Relations | #[belongs_to], #[has_many] and many-to-many via through = "junction" |
| Ownership Scoping | #[owner] generates find_by_id_scoped / list_by_owner / update_scoped / delete_scoped |
| Upsert | upsert(conflict = "…") generates INSERT ... ON CONFLICT DO UPDATE / DO NOTHING |
| Aggregate Roots | #[entity(aggregate_root)] with New{T} DTOs and transactional save |
| Transactions | Multi-entity atomic operations |
| Lifecycle Events | Created, Updated, Deleted events |
| Real-Time Streams | Postgres LISTEN/NOTIFY integration |
| Transactional Outbox | events(outbox) — durable at-least-once event delivery with retry/backoff |
| Lifecycle Hook Traits | {Entity}Hooks trait emitted with before_create / after_update / etc.; invocation is currently manual at your service layer (tracking auto-invocation: #127) |
| CQRS Commands | Business-oriented command pattern |
| Soft Delete | deleted_at timestamp support |
| Structured Logging | Opt-in tracing feature wraps every generated async method in #[tracing::instrument] with entity + op fields |
Documentation
| Topic | Languages |
|---|---|
| Getting Started | |
| Attributes | 🇬🇧 🇷🇺 🇰🇷 🇪🇸 🇨🇳 |
| Examples | 🇬🇧 🇷🇺 🇰🇷 🇪🇸 🇨🇳 |
| Features | |
| Filtering | 🇬🇧 🇷🇺 🇰🇷 🇪🇸 🇨🇳 |
| Relations | 🇬🇧 🇷🇺 🇰🇷 🇪🇸 🇨🇳 |
| Events | 🇬🇧 🇷🇺 🇰🇷 🇪🇸 🇨🇳 |
| Streams | 🇬🇧 🇷🇺 🇰🇷 🇪🇸 🇨🇳 |
| Hooks | 🇬🇧 🇷🇺 🇰🇷 🇪🇸 🇨🇳 |
| Commands | 🇬🇧 🇷🇺 🇰🇷 🇪🇸 🇨🇳 |
| Advanced | |
| Custom SQL | 🇬🇧 🇷🇺 🇰🇷 🇪🇸 🇨🇳 |
| Web Frameworks | 🇬🇧 🇷🇺 🇰🇷 🇪🇸 🇨🇳 |
| Best Practices | 🇬🇧 🇷🇺 🇰🇷 🇪🇸 🇨🇳 |
Quick Reference
Entity Attributes
Field Attributes
// Primary key (auto-generated UUID)
// Auto-generated (timestamps)
// Ownership column: adds *_scoped methods
// Include in CreateRequest
// Include in UpdateRequest
// Include in Response
// Exclude from all DTOs
// Exact match filter
// ILIKE pattern filter
// Range filter (from/to)
// Foreign key relation
// One-to-many relation
// Many-to-many via junction table
// Partial view
Transactional Outbox
LISTEN/NOTIFY (streams) is fire-and-forget: events are lost if no
subscriber is listening. events(outbox) makes delivery durable — every
generated write inserts the serialized event into the entity_outbox
table in the same transaction as the DML, and a drainer delivers rows
with retry and exponential backoff:
query.execute.await?;
;
new.run.await;
Rows are claimed with FOR UPDATE SKIP LOCKED (multiple drainers
cooperate), retried with exponential backoff and parked after
max_attempts for manual inspection. Delivery is at-least-once —
handlers must be idempotent. Composes with streams: NOTIFY wakes
subscribers instantly, the outbox guarantees nothing is lost. Requires
the outbox feature and serde_json in your crate.
Ownership Scoping
Mark the column carrying the owning principal's id with #[owner] and the
repository gains row-level scoped methods — "only this user's rows" without
hand-written predicates:
let mine: = pool.list_by_owner.await?;
let order = pool.find_by_id_scoped.await?; // None if not theirs
let updated = pool.update_scoped.await?; // None if not theirs
let removed = pool.delete_scoped.await?; // false if not theirs
Scoped reads and writes never reveal whether a row exists for another
owner, and all of them respect soft_delete.
Handler Guards
security = "..." only documents authentication in the OpenAPI spec. To
actually enforce it, pass a guard — any type implementing axum's
FromRequestParts. It is injected as a leading argument of every generated
handler, so a failed extraction rejects the request before the handler body
runs:
;
Per-operation overrides accept create, get, update, delete, list
and commands; the literal "none" disables the guard for that operation.
Commands listed in public = [...] never receive a guard.
Many-to-Many Relations
Declare the junction table with through and the repository gains a
JOIN-backed lookup plus link management, while migrations emits the
junction DDL (composite primary key, cascading foreign keys):
for ddl in MIGRATION_JUNCTIONS
pool.add_user.await?; // idempotent link
let members: = pool.find_users.await?;
let linked = pool.has_user.await?;
let removed = pool.remove_user.await?;
Postgres Enums
Derive ValueObject on a status-style enum and reference it from entities
with #[column(pg_enum = "...")]:
for ddl in MIGRATION_TYPES
query.execute.await?;
ValueObjectgeneratesPG_TYPEand idempotentPG_CREATE_TYPEconstants; the opt-insqlxflag additionally emitssqlx::Type/Encode/Decodeimpls so the enum binds and decodes without hand-written glue (omit it if you already derivesqlx::Typeyourself).#[column(pg_enum = "...")]sets the DDL column type and registers the enum's DDL in{Entity}::MIGRATION_TYPES— run those beforeMIGRATION_UP.- The declared name is checked against the enum's
pg_typeat compile time; a typo fails the build.
Upsert
Declare a conflict target with a uniqueness guarantee (#[id],
#[column(unique)] or unique_index(...)) and the repository gains an
upsert method backed by INSERT ... ON CONFLICT:
let user = pool.upsert.await?;
action = "update" (default) overwrites all non-conflict columns with the
incoming values (DO UPDATE SET col = EXCLUDED.col) and returns the
persisted row. action = "nothing" keeps the existing row (DO NOTHING)
and returns Option<Entity> — None when a conflicting row already
existed. Requires returning = "full" (the default). With streams
enabled, upsert publishes a Created notification for every row it
returns.
Transactions
Mark each participating entity with #[entity(table = "…", transactions)] and
drive a multi-entity transaction through Transaction::run. The closure
receives &mut TransactionContext; run commits on Ok and rolls back on
Err (or any panic) automatically:
use Transaction;
new
.run
.await?;
Need conditional commit/rollback inside the closure? Use
run_with_commit
— it takes TransactionContext by value so the closure can call
ctx.commit().await (or ctx.rollback().await) itself.
Tracing
Opt-in with the tracing feature. Every generated async method
(create, find_by_id, update, delete, list, find_by_<field>,
projections, transaction adapters, stream subscribers) is wrapped in
#[tracing::instrument(skip_all, fields(entity, op), err(Debug))].
= { = "0.14", = ["postgres", "tracing"] }
= "0.1"
= { = "0.3", = ["env-filter"] }
With a subscriber initialized, a failed User::create surfaces as:
ERROR entity.User.create: error=database error: duplicate key value violates unique constraint
in entity.User.create with entity="User" op="create"
When the feature is off, generated code is byte-for-byte identical to a build without the attribute — zero runtime cost.