@nathapp/nestjs-account-prisma
Prisma adapter for @nathapp/nestjs-account. Binds the core package's repository
tokens to AbstractPrismaRepository-based implementations.
Install
npm i @nathapp/nestjs-account-prisma
npm i -D prisma && npx prisma init
Schema
Append the 13 models from the packaged fragment
node_modules/@nathapp/nestjs-account-prisma/prisma/account.prisma to your app's
schema.prisma. The fragment carries no datasource or generator block — it
is models only. Every DateTime in it uses @db.Timestamptz(6) (PostgreSQL
timestamptz); bare DateTime is not supported.
PostgreSQL and MySQL. The fragment is authored for PostgreSQL 16 and also
supports MySQL 8.0. For MySQL, assemble it with @db.Timestamptz(6) rewritten
to @db.DateTime(6) (the only change; see the @nathapp/nestjs-iam-prisma
README, "Schema assembly and database support") and keep the MySQL server and
sessions on UTC (time_zone = '+00:00'), because DATETIME(6) stores no
timezone. Upgrading a MySQL database built from an earlier fragment: apply
prisma/sql/long-text-columns.mysql.sql (PostgreSQL needs nothing). Each
packaged migration has a migration.mysql.sql twin next to its migration.sql;
on MySQL the single-pending-transfer and single-pending-invitation guards are
functional unique indexes.
Two of the models are join tables (RolePermission, MembershipRole) that exist
to support the ROLE_REPOSITORY and MEMBERSHIP_ROLE_REPOSITORY bindings.
prisma/migrations/ in this package holds incremental patches.
20260714_ownership_transfer_pending_unique adds a partial unique index
enforcing a single pending ownership transfer per account:
CREATE UNIQUE INDEX ownership_transfers_one_pending_per_account
ON ownership_transfers (account_id)
WHERE status = 1;
20261118_invitations_one_pending_per_email adds the matching guard for
invitations — at most one PENDING invitation per (tenant_id, email):
CREATE UNIQUE INDEX invitations_one_pending_per_email
ON invitations (tenant_id, email)
WHERE status = 0;
Each patch ships PostgreSQL SQL (migration.sql) and a MySQL twin
(migration.mysql.sql). MySQL uses functional unique indexes that return NULL
for rows outside the pending state. These patches are deltas, not an initial
migration set. Include the required index DDL in your app's own migration
history; Prisma does not pick up the package's SQL files automatically. If you
are adding the ownership-transfer guard to an existing database, run this
preflight on PostgreSQL or MySQL and resolve any duplicates before creating the
index:
SELECT account_id, COUNT(*) FROM ownership_transfers WHERE status = 1
GROUP BY account_id HAVING COUNT(*) > 1;
Upgrade the invitation table from the previous fragment
The current fragment declares Invitation.email as @db.VarChar(320), the
INVITATION_EMAIL_MAX_LENGTH in @nathapp/nestjs-account. The invitation patch
changes the column from PostgreSQL text or MySQL VARCHAR(191) to
VARCHAR(320) before creating the pending-slot index. On MySQL the widened
index fits within InnoDB's limit (191 + 320 characters = 2044 bytes under utf8mb4).
-
Preflight on the old schema before any invitation upgrade DDL. Pause
invitation writers, including background jobs, and keep them paused through
the migration and app cutover. Run both the duplicate-slot query and the
oversized-email query for your provider:
-- Duplicate pending slots (both providers)
SELECT tenant_id, email, COUNT(*) FROM invitations WHERE status = 0
GROUP BY tenant_id, email HAVING COUNT(*) > 1;
-- Oversized emails (PostgreSQL)
SELECT id, length(email) FROM invitations WHERE length(email) > 320;
-- Oversized emails (MySQL)
SELECT id, CHAR_LENGTH(email) FROM invitations WHERE CHAR_LENGTH(email) > 320;
Resolve duplicates and correct oversized addresses with operator review. Do
not truncate automatically. Re-run both queries and proceed only when both
return no rows.
-
Prepare one consumer-owned migration on a development database. Update
the assembled schema to the new fragment and use
npx prisma migrate dev --create-only to draft the migration. In the draft's
migration.sql, replace Prisma's generated invitation email type change
with both statements from the matching provider file in
prisma/migrations/20261118_invitations_one_pending_per_email/. Review the
draft: it must change the width exactly once and create the slot index after
that change. Do not run plain migrate dev against the new fragment before
editing the draft, and do not run the packaged patch separately.
-
Deploy the reviewed migration from your app's migration history. On
each target database, repeat step 1 while it still has the old schema, then
run npx prisma migrate deploy. Regenerate the Prisma client from the new
fragment and deploy the updated app before resuming invitation writes.
For a fresh install using the current fragment, the base migration already
creates VARCHAR(320). Include only the provider's CREATE UNIQUE INDEX
statement for the invitation guard after the table is created, not the upgrade
ALTER TABLE.
Upgrade the onboarding flow unique key
The current fragment makes OnboardingFlow unique on (tenantId, appId, code)
instead of (appId, code), so each tenant can define its own flow with a given
code. PrismaOnboardingFlowRepository.findByCode(appId, code, tenantId) filters
by tenant.
The packaged prisma/migrations/20261128_onboarding_flow_tenant_unique/ holds
the PostgreSQL statements (migration.sql) and their MySQL twin
(migration.mysql.sql); or update the assembled schema to the new fragment and
run npx prisma migrate dev to generate the migration. Either way it drops the
old (app_id, code) unique index and creates the new one. The new key only widens
the old one, so existing rows cannot conflict and no preflight is needed.
Deploy it with npx prisma migrate deploy.
Invitation list index
The current fragment adds @@index([tenantId, createdAt]) to Invitation, matching the tenant
invitation list (tenantId filter, newest first). The packaged
prisma/migrations/20261126_invitations_tenant_created_at/ holds the PostgreSQL statement
(migration.sql) and its MySQL twin (migration.mysql.sql); or update the assembled schema and
run npx prisma migrate dev. It only adds an index, so no preflight is needed. Deploy it with
npx prisma migrate deploy.
Account list sort fields
PrismaAccountRepository.findByTenant accepts sortBy of createdAt, updatedAt, name,
type or status (exact spelling). Any other value is INVALID_SORT_FIELD (400) before a
query runs; no sortBy (or '') keeps newest first, and a sortOrder other than asc /
desc is asc.
Register
import { Module } from '@nestjs/common';
import { PrismaPg } from '@prisma/adapter-pg'; // MySQL: PrismaMariaDb from '@prisma/adapter-mariadb' (host/port/user/password/database, no connectionString)
import { PrismaClient } from './generated/prisma/client'; // your generator `output`
import { PrismaModule } from '@nathapp/nestjs-prisma';
import { AccountPrismaModule } from '@nathapp/nestjs-account-prisma';
@Module({
imports: [
PrismaModule.forRoot({
client: PrismaClient,
clientOptions: { adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL! }) },
transaction: true,
}),
AccountPrismaModule.register(),
],
})
export class AppModule {}
register() takes an optional options object:
| Option |
Type |
Default |
Meaning |
global |
boolean |
true |
Register as a global module so the repository tokens resolve anywhere. |
register() is the only import form for this adapter. There is no registerAsync.
If you already wrap this adapter in @Global()
Pass global: false. Otherwise the adapter's own global exports are injected
in addition to your override, and last-registration-wins silently decides
which implementation is used:
import { Global, Module } from '@nestjs/common';
import { ACCOUNT_REPOSITORY } from '@nathapp/nestjs-account';
import { AccountPrismaModule } from '@nathapp/nestjs-account-prisma';
import { SoftDeleteAccountRepository } from './soft-delete-account.repository';
@Global()
@Module({
imports: [AccountPrismaModule.register({ global: false })],
providers: [{ provide: ACCOUNT_REPOSITORY, useClass: SoftDeleteAccountRepository }],
exports: [ACCOUNT_REPOSITORY],
})
export class PrismaOverridesModule {}
global: false only helps if the adapter is registered once. A second, global
register() elsewhere in the app keeps its global exports, and global: false
here does not remove them — so the collision this section exists to prevent is
still there. Register the adapter in exactly one place.
The global option carries no documentation in the published type definitions
(removeComments: true strips the JSDoc from the emitted .d.ts), so this README
is where it is described. The options object is typed as PrismaAdapterModuleOptions,
which is exported from this package if you need to name the type.
Transactions
Multi-write flows need PrismaModule.forRoot({ client: PrismaClient, transaction: true })
with PrismaClient imported from your generated client (Prisma 7 prisma-client generator).
Every repository resolves its client per operation from the TRANSACTION_MANAGER
token, and the two PrismaModule registration paths fail differently when
transaction is omitted:
PrismaModule.forRoot() binds TRANSACTION_MANAGER only when transaction: true
is set. Without it nothing is bound, the repositories cannot resolve their
dependency, and Nest fails at boot.
PrismaModule.forRootAsync() always binds the token, but with a manager whose
run() and getClient() throw and whose isInTransaction() returns false, so
the app boots and fails on first use instead.
Neither path is a silent passthrough: a real transaction manager either joins the
transaction already in scope or opens a Prisma interactive transaction.
Both of those are PrismaModule from @nathapp/nestjs-prisma. These adapters
expose only the synchronous register(); they have no registerAsync.
Tokens bound
| Token |
Implementation |
ACCOUNT_REPOSITORY |
PrismaAccountRepository |
MEMBERSHIP_REPOSITORY |
PrismaMembershipRepository |
ROLE_REPOSITORY |
PrismaRoleRepository |
PERMISSION_REPOSITORY |
PrismaPermissionRepository |
INVITATION_REPOSITORY |
PrismaInvitationRepository |
PROFILE_REPOSITORY |
PrismaProfileRepository |
ONBOARDING_FLOW_REPOSITORY |
PrismaOnboardingFlowRepository |
ONBOARDING_PROGRESS_REPOSITORY |
PrismaOnboardingProgressRepository |
TENANT_APP_REPOSITORY |
PrismaTenantAppRepository |
MEMBERSHIP_ROLE_REPOSITORY |
PrismaMembershipRoleRepository |
AUDIT_LOG_REPOSITORY |
PrismaAuditLogRepository |
OWNERSHIP_TRANSFER_REPOSITORY |
PrismaOwnershipTransferRepository |
Onboarding is split across two tokens — ONBOARDING_FLOW_REPOSITORY for flow
definitions and ONBOARDING_PROGRESS_REPOSITORY for per-account progress — not
one combined token.