bug(migration): db migrate fails — an extension contract space's RLS policies are reported as extra by the app space's schema check

Open
#31,233 3 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

@ShivamJuyal24 is already working on this.

Since Nov 27, 2026.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
45/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Active
Tech stack
postgresql, typescript

Research direction

Start by reproducing the failure with the two contract spaces described in the issue, then trace the schema check after apply that reports the extension's RLS policy as extra. Compare how it scopes tables and policies to contract spaces; the issue notes that tables are excluded from the app space's comparison while policies are not. Done means both migrations apply and prisma db verify passes with the extension policy present.

Written by the indexing model from the issue text.

Description

Package and version

@prisma/[email protected], [email protected] (CLI), @prisma/[email protected]

What happened?

An app contract builds on an extension contract space that declares an RLS policy. prisma db migrate on an empty database runs both spaces' migrations, then the schema check after apply reports the extension's policy as extra, and nothing is applied:

✘ [MIGRATION.SCHEMA_VERIFY_FAILED] Database schema does not satisfy contract (1 failure)
  why: The schema check after apply found: extra: database/public/Account/Account_tenant_1d072ab3. The failed apply changed nothing.

The extension's table public.Account is not reported, only its policy. The app's plan creates schema public as well as ext, so the app space seems to claim public. The check after apply then appears to compare the app space's contract with everything in public. It leaves tables of other spaces out of that comparison, but not policies on those tables.

With the policy removed from the extension and nothing else changed, db migrate reports Applied 2 migration(s) (8 operation(s)) across 2 contract space(s) and prisma db verify passes.

What did you expect to happen?

A policy that the extension space declares on its own table is checked against that space's contract, not reported as extra for the app space, and db migrate applies both spaces.

Minimal reproduction

Two folders under one package.json: base/ is the extension contract space and app/ is the app built on it. base/space.ts turns the base's emitted contract and migrations into an extension descriptor by hand, following the ContractSpace and ControlExtensionDescriptor types. We found no documented way to package an internal contract as an extension space; if there is one, we'll gladly use it.

  1. Run CREATE ROLE app_user NOLOGIN;, create an empty database and set DATABASE_URL to it.
  2. In base/: prisma contract emit, then prisma migration plan --name init.
  3. In app/: prisma contract emit, which writes migrations/base/. Then prisma migration plan --name init, then prisma db migrate --no-advance-ref. It fails with the output above, and the database stays empty.
  4. Remove the policyAll(...) entity from base/src/contract.ts and repeat steps 2–3 on a new empty database. db migrate applies both spaces and prisma db verify passes.

package.json

{
  "type": "module",
  "dependencies": {
    "@prisma/orm-postgres": "8.0.0-rc.25"
  },
  "devDependencies": {
    "@prisma/cli-engine": "0.10.4",
    "prisma": "8.0.0-rc.36"
  }
}

base/prisma.config.ts

import { definePrismaConfig } from '@prisma/cli-engine';
import { defineConfig as ormConfig } from '@prisma/orm-postgres/config';

export default definePrismaConfig({
  orm: ormConfig({
    contract: './src/contract.ts',
    output: './src/generated',
    db: { connection: process.env['DATABASE_URL']! },
  }),
});

base/src/contract.ts

import {
  defineContract,
  field,
  model,
  policyAll,
  rlsEnabled,
  role,
  sql,
  type,
} from '@prisma/orm-postgres/contract-builder';

const appUser = role('app_user');

const Account = model('Account', {
  fields: {
    id: field.column(type.Uuid()).id(),
    tenantId: field.column(type.Uuid()),
  },
});

const sameTenant = sql`"tenantId" = nullif(current_setting('app.tenant', true), '')::uuid`;

export const contract = defineContract(
  {
    entities: [
      appUser,
      rlsEnabled(Account),
      policyAll(Account, { name: 'Account_tenant', roles: [appUser], using: sameTenant, withCheck: sameTenant }),
    ],
  },
  () => ({ models: { Account } }),
);

base/space.ts

// The base contract and its migrations as an extension contract space, `base`.
import { readdirSync, readFileSync } from 'node:fs';

const root = new URL('./', import.meta.url);
const read = (path: string): unknown => JSON.parse(readFileSync(new URL(path, root), 'utf8'));

const migrations = readdirSync(new URL('migrations/app/', root), { withFileTypes: true })
  .filter((entry) => entry.isDirectory())
  .map((entry) => entry.name)
  .sort()
  .map((dirName) => ({
    dirName,
    metadata: read(`migrations/app/${dirName}/migration.json`),
    ops: read(`migrations/app/${dirName}/ops.json`),
  }));

export default {
  kind: 'extension',
  id: 'base',
  familyId: 'sql',
  targetId: 'postgres',
  version: '0.0.0',
  contractSpace: {
    contractJson: read('src/generated/contract.json'),
    migrations,
    headRef: { hash: (migrations.at(-1)?.metadata as { to: string }).to, invariants: [] },
  },
  create: () => ({ familyId: 'sql', targetId: 'postgres' }),
} as const;

app/prisma.config.ts

import { definePrismaConfig } from '@prisma/cli-engine';
import { defineConfig as ormConfig } from '@prisma/orm-postgres/config';

import base from '../base/space.ts';

export default definePrismaConfig({
  orm: ormConfig({
    contract: './src/contract.prisma',
    output: './src/generated',
    extensions: [base],
    db: { connection: process.env['DATABASE_URL']! },
  }),
});

app/src/contract.prisma

// use prisma-8

namespace ext {
  model Note {
    id        Uuid                @id
    accountId Uuid
    account   base:public.Account @relation(fields: [accountId], references: [id], onDelete: Cascade)
  }
}

The app's plan:

CREATE SCHEMA IF NOT EXISTS "ext";
CREATE SCHEMA IF NOT EXISTS "public";
CREATE TABLE "ext"."Note" (
  "accountId" uuid NOT NULL,
  "id" uuid NOT NULL,
  PRIMARY KEY ("id")
);
CREATE INDEX "Note_accountId_idx_cbfb3085" ON "ext"."Note" ("accountId");
ALTER TABLE "ext"."Note"
ADD CONSTRAINT "Note_accountId_fkey"
FOREIGN KEY ("accountId")
REFERENCES "public"."Account" ("id")
ON DELETE CASCADE;

Environment

  • Node: v26.13.1
  • OS: darwin (macOS 27.0.1)
  • Package manager: pnpm 12.23.0
  • Database: PostgreSQL 17.11

Additional context

Our use case: one product sold two ways. One is a core alone, self-hosted, with RLS for multi-tenancy. The other is the core plus a SaaS layer whose tables live in their own schema and refer to the core's tables. The core can't depend on the SaaS layer, so the core is the extension contract space and the SaaS layer is the app built on it. The core declares dozens of RLS policies, and the apply fails with one extra per policy.

Related: #31003 (RLS multi-tenancy in core).

Dominant language
TypeScript
Stars
47.8k
Forks
2.6k
Avg merge
1d 21h
Merged PRs (30d)
227

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from prisma/orm

All issues in prisma/orm

Similar issues

More TypeScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.