Skip to content

Persist through Postgres

Start Postgres, apply the post table's migration, run the binary on the data layer blog imports — mutating routes commit in a transaction; failures roll back.

You start Postgres and apply the post table’s migration, and the data layer blog imports comes alive. By the end of this page, the five CRUD routes mount, POST /posts persists inside a transaction a failing handler rolls back, and the e2e suite of Test it end to end has a database to point at.

nestrs g resource wrote the data layer’s one import into blog’s root on page 2: SeaOrmDatabaseModule binds the unit of work each request and job runs in, over the pool SeaOrmModule opens from <PREFIX>_SEAORM__URL. Every route #[crud] generates runs its Repo call inside one, so an app importing PostsHttpModule without the binding never boots: the access graph refuses it, naming the line to add. The crates are nest-rs-database, the store-agnostic seam, and nest-rs-seaorm, its implementation on SeaORM.

No manifest line moves: the workspace’s nest-rs already carries seaorm, and http beside it turns on the hooks the HTTP data layer needs.

nestrs new ships a migrations crate holding every SeaORM migration, plus the migrate binary the nestrs run db … verbs drive. nestrs g resource wrote the post table’s migration into it on page 2, from the entity’s column list, and registered it in both lib.rs and migrator.rs, regenerated from lib.rs’s list so the two can never disagree:

  • Directorycrates/migrations/
    • Directorysrc/
      • lib.rs
      • migrator.rs
      • m20260609_000000_create_posts.rs
      • Directorybin/
        • migrate.rs

It creates the columns Post declares, the key and the three timestamps timestamps and soft_delete read included, each in the builder and as a variant of the enum, which DeriveIden writes into the DDL:

crates/migrations/src/m20260609_000000_create_posts.rs
use sea_orm_migration::prelude::*;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(Post::Table)
.if_not_exists()
.col(ColumnDef::new(Post::Id).uuid().not_null().primary_key())
.col(ColumnDef::new(Post::Title).string().not_null())
.col(ColumnDef::new(Post::Body).text().not_null())
.col(
ColumnDef::new(Post::CreatedAt)
.timestamp_with_time_zone()
.not_null()
.default(Expr::current_timestamp()),
)
.col(
ColumnDef::new(Post::UpdatedAt)
.timestamp_with_time_zone()
.not_null()
.default(Expr::current_timestamp()),
)
.col(
ColumnDef::new(Post::DeletedAt)
.timestamp_with_time_zone()
.null(),
)
.to_owned(),
)
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(Post::Table).to_owned())
.await
}
}
// `DeriveIden` snake-cases these into SQL: this enum writes the
// `post` table and its columns. Rename it if your entity's
// `#[sea_orm(table_name = "…")]` says otherwise — the two must agree.
#[derive(DeriveIden)]
enum Post {
Table,
Id,
Title,
Body,
CreatedAt,
UpdatedAt,
DeletedAt,
}

The file name carries the day you ran nestrs g resource; yours differs from the one above. A later change to the table takes a migration of its own, named for what it does — nestrs g migration add_status_to_posts writes one for you to fill (Migrations) — since the database that applied this one never runs it again.

nestrs new scaffolds a compose.yml with Postgres, Valkey and an S3 object store, and the committed .env.development and .env.test already point <PREFIX>_SEAORM__URL at it — never .env, which production reads too, so a deployment cannot fall back to a plaintext local URL. The credentials are the workspace name, not the app’s — a workspace scaffolded with nestrs new hello gets postgres://hello:hello@localhost:5432/hello?sslmode=disable, whatever its apps are called. Bring the services up once — blog reaches Postgres alone; the store and Valkey wait for a feature that needs them:

Terminal window
$ docker compose up -d
✔ Container hello-postgres-1 Started
✔ Container hello-redis-1 Started
✔ Container hello-storage-1 Healthy
✔ Container hello-storage-buckets-1 Started
$ nestrs run db up
INFO sea_orm_migration::migrator::exec: Applying migration 'm20260609_000000_create_posts'
INFO sea_orm_migration::migrator::exec: Migration 'm20260609_000000_create_posts' has been applied

nestrs run db up runs Migrator::up against <PREFIX>_SEAORM__URL, read through connect_from_env off the .env cascade the apps read, so a tool and its app never point at different databases; db.just declares the development profile for every db recipe, as nestrs run dev does for the app.

Transactions wrap mutating routes automatically

Section titled “Transactions wrap mutating routes automatically”

Every request runs in the unit of work SeaOrmDatabaseModule binds, which reads the HTTP method and installs the right executor before the handler runs:

HTTP methodAmbient executor
GET / HEAD / OPTIONS / TRACEPool — no transaction, each statement commits on its own
POST / PATCH / PUT / DELETETransaction, opened on the first statement — committed on 2xx/3xx, rolled back otherwise

The contract you write code against: on a mutating method, every success commits and every error response unwinds. A safe method has nothing to unwind — a GET that writes keeps its write, whatever it answers. No tx.begin() / tx.commit() in the service.

Terminal window
$ nestrs run dev blog
INFO nest_rs::app: app starting app="blog" version="0.1.0" framework="7.0.0"
INFO nest_rs::orm: connecting to database endpoint=localhost:5432 max_connections=10
INFO nest_rs::app: app ready transports="http" addresses="0.0.0.0:3001"

connecting to database names Postgres by host and port, never by its URL, which carries the credentials; refused credentials stop the boot at once.

The nest_rs::routes target prints every mount: the full CRUD surface of one #[crud] block, with no handler body written, beside the development token route:

Terminal window
INFO nest_rs::routes: mounted host="DevTokenController" method="dev_token" verb="POST" path="/auth/dev-token"
INFO nest_rs::routes: mounted host="PostsController" method="list" verb="GET" path="/posts"
INFO nest_rs::routes: mounted host="PostsController" method="create" verb="POST" path="/posts"
INFO nest_rs::routes: mounted host="PostsController" method="get" verb="GET" path="/posts/{id}"
INFO nest_rs::routes: mounted host="PostsController" method="update" verb="PUT" path="/posts/{id}"
INFO nest_rs::routes: mounted host="PostsController" method="delete" verb="DELETE" path="/posts/{id}"

Every route is behind the guards nestrs g resource bound, which you read on the previous page, so an anonymous call stops at the door:

Terminal window
$ curl -s -o /dev/null -w '%{http_code}\n' http://localhost:3001/posts
401
Terminal window
WARN nest_rs::authn: guard denied the request guard="AuthnGuard<JwtStrategy<Claims>>" unit="http.request" host="PostsController" method="list" verb="GET" path="/posts" status=401 reason="missing_credentials" error="missing credentials" trace_id=01a190f2f5e277bda79f735006bdcc6b span_id=0b5f30d871801957

One denial, one line, naming the route by its mounted line’s fields, with the request’s trace_id and no actor_id. Drop #[use_guards(...)] and the boot refuses instead, naming every route no guard covers.

A call needs a bearer token. The auth adapter’s development route mints one, signed with the <PREFIX>_AUTHN__SECRET drawn into .env.local and issued by blog to itself (its origin, which apps/blog/.env names as both issuer and audience):

Terminal window
$ TOKEN=$(curl -s -X POST http://localhost:3001/auth/dev-token \
-H 'Content-Type: application/json' -d '{}' | jq -r .access_token)

Pass {"roles": ["admin"]} for an admin token, or a sub to pin the subject. The real login is yours to write — what counts as a credential and where users live are domain decisions, and Add a login route is the pattern.

Terminal window
$ curl -s -X POST http://localhost:3001/posts -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"title":"Hello","body":"World"}'
{"id":"019f9bd5-725d-7ee2-8031-b45d3aa4cc7a","title":"Hello","body":"World","created_at":"2026-…","updated_at":"2026-…"}
$ curl -s http://localhost:3001/posts -H "Authorization: Bearer $TOKEN"
[{"id":"019f9bd5-725d-7ee2-8031-b45d3aa4cc7a","title":"Hello","body":"World","created_at":"2026-…","updated_at":"2026-…"}]

Both calls ran under the caller’s ability, as every read does since the previous page: drop the ab.can(Action::Manage, post::Entity) you added there and the same two calls answer 403 with an empty table behind them. blog’s rule is one blanket grant; Secure your posts narrows it.

  • Postgres running beside blog, and the data layer g resource wired — the five CRUD routes mount.
  • The post table’s migration, applied through nestrs run db up.
  • POST /posts persisting into Postgres inside an automatic transaction, scoped by the caller’s ability.
  • Validate inputs — the next step: reject a bad body with a structured 400.
  • CRUD — the reference page for Repo, CrudService, and transactions.