Skip to content

Entities

The entity is the wire contract. One #[expose]d SeaORM model emits the DTO, inputs, JSON schema, relation loaders, and lifecycle — opt-in, fail-secure.

An entity is a SeaORM model decorated with #[expose]. You declare the columns, their types, the relations, and which fields cross the wire — once. The macro emits everything downstream:

  • the wire DTO, and the create/update inputs;
  • the validator wiring;
  • the JSON schema the HTTP and OpenAPI layers read;
  • the GraphQL object and its relation dataloaders;
  • the lifecycle behaviour — timestamps, soft delete.

The entity is the wire contract. There is no separate DTO to keep in sync — a column reaches a transport only when it carries #[expose], and silence means hidden. That is the deliberate posture: a column a later migration adds never leaks by omission.

Building your first entity? Start with the tutorial walkthrough — it grows a minimal Post step by step. This page is the reference: every header flag and every field attribute. The inputs and their validation are on Entity inputs, the lifecycle columns on Lifecycle columns, and relations on Relations and computed fields.

The demo’s reference entity lives at crates/features/src/posts/entities/post.rs, whose folder holds a second entity; a feature with one keeps it in entity.rs, as below. Copy it before inventing a second shape.

crates/features/src/posts/entity.rs
use nest_rs::seaorm::expose;
use sea_orm::entity::prelude::*;
#[expose(
name = "Post",
service = super::service::PostsService,
graphql,
soft_delete,
timestamps
)]
#[sea_orm::model]
#[derive(Clone, Debug, DeriveEntityModel)]
#[sea_orm(table_name = "post")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
#[expose]
pub id: Uuid,
#[expose]
pub org_id: Uuid,
#[expose]
pub author_id: Uuid,
#[expose(input(create, update), validate(length(min = 1)))]
pub title: String,
#[expose(input(create, update), validate(length(min = 1)))]
pub body: String,
#[expose]
pub created_at: DateTimeWithTimeZone,
#[expose]
pub updated_at: DateTimeWithTimeZone,
pub deleted_at: Option<DateTimeWithTimeZone>,
#[sea_orm(belongs_to, from = "org_id", to = "id")]
#[expose]
pub org: HasOne<crate::orgs::Entity>,
#[sea_orm(belongs_to, from = "author_id", to = "id")]
#[expose]
pub author: HasOne<crate::users::Entity>,
}

SeaORM owns the column types and the #[sea_orm(...)] attributes — #[expose] only reads them and decides what crosses the wire. The two decorators compose: #[sea_orm::model] builds the Entity, Column, ActiveModel, and Relation machinery; #[expose] builds the transport surface on top. The Model crosses no wire: #[expose] writes the wire type, judged on the whole row where it is built, and refuses a Serialize, Deserialize or JsonSchema on the row, derived or written by hand, and with the graphql feature a SimpleObject or InputObject too, so it serializes nowhere but as Post, and a hidden column has no way onto a wire. A route, a message, a GraphQL field, a tool or a resource answering any Model — one no #[expose] decorates included, whatever it derives, inside a Json, a Vec, an Option or a stream — fails to compile at its type, a row crosses no wire. What stays yours is a body serializing a row by hand: serde_json::to_value(&row), a push, a DTO holding the row in a field. For everything about columns, types, relations, and migrations, the official SeaORM 2 documentation is the source of truth.

#[expose(...)] takes one required value, one near-required path, and a set of bare flags.

FlagKindEffect
name = "Post"requiredThe wire DTO / GraphQL object / OpenAPI schema name. The entity names it as <Entity as Exposed>::Wire, which is what a #[crud] operation answers; only #[expose] implements Exposed.
service = …pathThe service that owns the entity. Required as soon as the entity exposes a relation or another feature needs its PK loader — it’s where the macro emits the loaders.
graphqlflagEmit the GraphQL object + input objects, and auto-resolve exposed relations through dataloaders. An exposed relation without graphql is a compile error.
timestampsflagEmit an ActiveModelBehavior that stamps created_at on insert and, when the entity has one, updated_at on every save. Requires created_at: an append-only entity has no updated_at.
soft_deleteflagDeletes set deleted_at, and every Repo read hides a tombstoned row. Requires a deleted_at: Option<…> column.
complexflagForce #[graphql(complex)] on the wire DTO. Auto-enabled when graphql is set and the entity has auto-resolved relations — you rarely set it by hand.

A field crosses HTTP, GraphQL, and WS only when it carries #[expose]. No attribute means the field is hidden from every transport.

Field attributeOn the wireIn inputs
#[expose]yes (read-only)no
#[expose(input(create))]yesCreate<Name> only
#[expose(input(update))]yesUpdate<Name> only
#[expose(input(create, update))]yesboth
(no #[expose])hiddenno

input(...) implies read — a writable field is always readable. The ordering of create / update is free.

Hidden columns are the security-load-bearing case. A password_hash, a role set from a JWT, an internal flag — none of these should ride a response. Because exposure is opt-in, they stay off the wire by default, and a column a future migration adds never leaks until someone deliberately exposes it.

The wire is not the only place a secret prints: the Model and the ActiveModel derive Debug, so a log line can print a row. Type a secret column as nest_rs::core::Secret — its Debug and its serialization both say <redacted>, and the column stores and reads its value’s own type:

crates/features/src/users/entities/user.rs (from the demo, abridged)
use nest_rs::core::Secret;
// …
#[derive(Clone, Debug, DeriveEntityModel)]
// …
pub struct Model {
// …
pub password_hash: Option<Secret<String>>,
// …
}

The service that verifies the hash reads it with expose_secret(), and #[expose] refuses a Secret column at compile time: a secret never crosses the wire.

An exposed column whose type is your own enum passes through to the wire verbatim, so the enum is what has to carry the wire traits. #[wire_enum], beside #[input] and #[output] in nest_rs::core, emits all of them — Serialize, Deserialize, JsonSchema, and under graphql async_graphql::Enum, plus the Clone/Copy/Eq shape those require:

crates/features/src/posts/entities/post.rs
use nest_rs::core::wire_enum;
use nest_rs::seaorm::expose;
use sea_orm::entity::prelude::*;
#[wire_enum(graphql)]
#[derive(EnumIter, DeriveActiveEnum)]
#[sea_orm(rs_type = "String", db_type = "String(StringLen::None)")]
#[serde(rename_all = "lowercase")]
pub enum PostStatus {
#[sea_orm(string_value = "draft")]
Draft,
#[sea_orm(string_value = "published")]
Published,
}

Each of those derives expands against the call site’s prelude, so hand-writing them put schemars and async-graphql in your manifest for code you never wrote. The decorator routes them back through the framework with a crate = override, so your manifest names neither. Its graphql key needs the graphql feature, and a build without it says so.

It deliberately emits nothing from SeaORM: EnumIter, DeriveActiveEnum, #[sea_orm(rs_type, db_type)] and the per-variant string_value stay yours, because how the column is stored is your decision, not the wire’s. Your own #[serde(rename_all = …)] and #[derive(Default)] sit beside it untouched. Drop graphql for an enum that only crosses HTTP.

An enum a hidden column holds never crosses a wire, so it takes no #[wire_enum]: SeaORM’s derives are its own, as the users exemplar’s role shows.

AttributeWhereEffect
#[expose]any columnRead-only on the wire.
#[expose(input(create, update))]scalar columnAdds to wire + the named input(s).
#[expose(validate(…))]input columnAttaches a validator rule to the input field.
#[expose(complexity = …)]exposed field / relationOverrides the GraphQL complexity cost (literal or expression string).
#[expose(default = …)]a column the create input does not carryThe value every insert through Repo leaving the column unset stores.
#[expose(nullable)]an exposed column of a type with no nullA grant on Read may withhold it: its wire field is an Option, nullable in every edge’s schema, its key always written.
#[expose] on HasOne/HasManyrelationAuto-resolved GraphQL field (needs header graphql + service).
#[expose(via = "…")]HasManyNames which of the child’s foreign keys the relation follows — required when it has two to this parent.
#[wire_enum] / #[wire_enum(graphql)]a column’s enum typeEmits the wire derives (serde, schemars, async-graphql Enum) routed through the framework.
  • Entity checklist — every decision one #[expose]d entity asks of you, one line each.
  • CRUD — #[crud] generates the endpoints over the entity’s service.
  • Response masking — what unexposed columns and their placeholders are for.
  • SeaORM 2 documentation — the reference for the columns, relations and migrations under #[expose].