GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(p2002): correct modelName in nested create unique constraint errors #29595 by AnupamKumar-1 · Pull Request #29628 · prisma/orm

fix(p2002): correct modelName in nested create unique constraint errors #29595 #29628

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
aqrln merged 13 commits into prisma:main from AnupamKumar-1:fix/29595-p2002-nested-modelname
Jul 28, 2026

Uh oh!

There was an error while loading. Please reload this page.

Merged

fix(p2002): correct modelName in nested create unique constraint errors #29595 #29628

Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
13 commits
Select commit Hold shift + click to select a range
25ec568
fix(p2002): correct modelName in nested create unique constraint errors
AnupamKumar-1 Jun 8, 2026
436b98f
Merge branch 'main' into fix/29595-p2002-nested-modelname
AnupamKumar-1 Jun 8, 2026
4f69e7c
Fix @@map model name resolution for nested P2002 errors
AnupamKumar-1 Jul 21, 2026
15473d0
Handle P2002 modelName resolution across adapters
AnupamKumar-1 Jul 21, 2026
cf04b6a
Fix MSSQL parsing and qualified model resolution
AnupamKumar-1 Jul 21, 2026
7ec509b
Merge remote-tracking branch 'origin/main' into fix/29595-p2002-neste…
tensordreams Jul 22, 2026
368c585
Refine P2002 table extraction and table->model mapping
tensordreams Jul 23, 2026
979276e
Merge origin/main into fix/29595-p2002-nested-modelname
tensordreams Jul 23, 2026
9b47584
test(adapter-pg): expect derived table for default-named constraint (…
tensordreams Jul 23, 2026
b73aa17
fix(client): carry per-model schema in runtime data model for P2002 m…
tensordreams Jul 24, 2026
a90a7b2
Merge remote-tracking branch 'origin/main' into worktree-agent-a59fba…
tensordreams Jul 24, 2026
7d609fa
Merge remote-tracking branch 'origin/main' into fix/29595-p2002-neste…
tensordreams Jul 27, 2026
cb5e35f
test(client): update Prisma.dmmf snapshot for pruned model schema field
tensordreams Jul 27, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view
Prev Previous commit
Next Next commit
fix(client): carry per-model schema in runtime data model for P2002 m…
…apping

Add each model's `@@schema` value to the (pruned) runtime data model and use
it in `modelNameForTable` so that two models mapped to the same table name in
different database schemas resolve to the correct Prisma model name for P2002
`meta.modelName`, instead of giving up and falling back to the top-level model.

The query compiler's DMMF already emits per-model `schema`; only the
client-side pruning dropped it, so no engine change is required. When the
reported table is not schema-qualified the lookup keeps the previous
bare-table behavior and still returns `undefined` on genuine ambiguity.

Also rewrite the P2002 table-forwarding unit test to assert via
`expect(...).toThrow` instead of a manual try/catch.
  • Loading branch information

Uh oh!

There was an error while loading. Please reload this page.

@tensordreams
tensordreams committed Jul 24, 2026
commit b73aa17ed4d0cfa7d52a5bdb813e46712d08cdb9

There are no files selected for viewing

3 changes: 2 additions & 1 deletion 3 packages/client-common/src/runtimeDataModel.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export type RuntimeDataModel = {

export type PrunedRuntimeModel = {
readonly dbName: RuntimeModel['dbName']
readonly schema: RuntimeModel['schema']
readonly fields: Pick<RuntimeModel['fields'][number], 'name' | 'kind' | 'type' | 'relationName' | 'dbName'>[]
}

Expand All @@ -37,7 +38,7 @@ export function pruneRuntimeDataModel({ models }: RuntimeDataModel) {
const prunedModels: PrunedRuntimeDataModel['models'] = {}

for (const modelName of Object.keys(models)) {
prunedModels[modelName] = { fields: [], dbName: models[modelName].dbName }
prunedModels[modelName] = { fields: [], dbName: models[modelName].dbName, schema: models[modelName].schema }

for (const { name, kind, type, relationName, dbName } of models[modelName].fields) {
prunedModels[modelName].fields.push({ name, kind, type, relationName, dbName })
Expand Down
16 changes: 7 additions & 9 deletions 16 packages/client-engine-runtime/src/user-facing-error.test.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -202,13 +202,11 @@ test('rethrowAsUserFacing forwards the violated table for unique constraint viol
table: 'app_major_versions',
})

try {
rethrowAsUserFacing(error)
throw new Error('expected rethrowAsUserFacing to throw')
} catch (e) {
expect(e).toBeInstanceOf(UserFacingError)
const userFacing = e as UserFacingError
expect(userFacing.code).toBe('P2002')
expect(userFacing.meta).toMatchObject({ table: 'app_major_versions', driverAdapterError: error })
}
expect(() => rethrowAsUserFacing(error)).toThrow(UserFacingError)
expect(() => rethrowAsUserFacing(error)).toThrow(
expect.objectContaining({
code: 'P2002',
meta: expect.objectContaining({ table: 'app_major_versions', driverAdapterError: error }),
}),
)
})
23 changes: 2 additions & 21 deletions 23 packages/client/src/runtime/RequestHandler.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import { CallSite } from './utils/CallSite'
import { createErrorMessageWithContext } from './utils/createErrorMessageWithContext'
import { deepGet } from './utils/deep-set'
import { deserializeRawResult, RawResponse } from './utils/deserializeRawResults'
import { modelNameForTable } from './utils/modelNameForTable'

const debug = Debug('prisma:client:request_handler')

Expand Down Expand Up @@ -281,32 +282,12 @@ export class RequestHandler {
delete meta.table

const modelName =
this.modelNameForTable(errorMeta.table) ??
modelNameForTable(this.client._runtimeDataModel, errorMeta.table) ??
(typeof meta.modelName === 'string' ? meta.modelName : topLevelModelName)

return modelName !== undefined ? { ...meta, modelName } : meta
}

/**
* Maps a physical table name reported by a driver adapter back to the name
* of the Prisma model backed by that table, taking `@@map` into account.
* Returns `undefined` when no model, or more than one model, matches.
*/
private modelNameForTable(table: string): string | undefined {
// `dbName` is always the bare table name, while a driver adapter may
// report the table schema-qualified (e.g. `public.users`), so compare
// only the last `.`-separated segment of the reported name.
const tableName = table.split('.').pop()
const matches = Object.entries(this.client._runtimeDataModel.models).filter(
([name, model]) => (model.dbName ?? name) === tableName,
)
// With `@@schema`, models in different schemas can share a table name.
// The runtime data model carries no schema information, so an ambiguous
// match cannot be resolved — report no match instead of guessing, which
// makes the caller fall back to the top-level operation's model name.
return matches.length === 1 ? matches[0][0] : undefined
}

sanitizeMessage(message) {
if (this.client._errorFormat && this.client._errorFormat !== 'pretty') {
return stripAnsi(message)
Expand Down
54 changes: 54 additions & 0 deletions 54 packages/client/src/runtime/utils/modelNameForTable.test.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import type { RuntimeDataModel } from '@prisma/client-common'

import { modelNameForTable } from './modelNameForTable'

type TestModel = { dbName?: string | null; schema?: string | null }

function runtimeDataModel(models: Record<string, TestModel>): RuntimeDataModel {
const builtModels = Object.fromEntries(
Object.entries(models).map(([name, { dbName = null, schema = null }]) => [name, { dbName, schema, fields: [] }]),
)
return { models: builtModels, enums: {}, types: {} } as unknown as RuntimeDataModel
}

describe('modelNameForTable', () => {
test('resolves an unmapped model by its bare table name', () => {
const dataModel = runtimeDataModel({ User: {} })
expect(modelNameForTable(dataModel, 'User')).toBe('User')
})

test('resolves a @@map-ped model to its Prisma model name', () => {
const dataModel = runtimeDataModel({ AppMajorVersion: { dbName: 'app_major_versions' } })
expect(modelNameForTable(dataModel, 'app_major_versions')).toBe('AppMajorVersion')
})

test('ignores the schema qualifier of the reported table when the match is unambiguous', () => {
const dataModel = runtimeDataModel({ User: { dbName: 'users', schema: 'public' } })
expect(modelNameForTable(dataModel, 'public.users')).toBe('User')
})

test('disambiguates models sharing a table name across schemas by the reported schema', () => {
const dataModel = runtimeDataModel({
User: { dbName: 'some_table', schema: 'base' },
Post: { dbName: 'some_table', schema: 'transactional' },
})
expect(modelNameForTable(dataModel, 'base.some_table')).toBe('User')
expect(modelNameForTable(dataModel, 'transactional.some_table')).toBe('Post')
})

test('returns undefined when a shared table name cannot be disambiguated', () => {
const dataModel = runtimeDataModel({
User: { dbName: 'some_table', schema: 'base' },
Post: { dbName: 'some_table', schema: 'transactional' },
})
// Bare table name (no schema reported) -> ambiguous -> caller falls back.
expect(modelNameForTable(dataModel, 'some_table')).toBeUndefined()
// Reported schema matches no model.
expect(modelNameForTable(dataModel, 'other.some_table')).toBeUndefined()
})

test('returns undefined when no model maps to the reported table', () => {
const dataModel = runtimeDataModel({ User: { dbName: 'users' } })
expect(modelNameForTable(dataModel, 'unknown_table')).toBeUndefined()
})
})
46 changes: 46 additions & 0 deletions 46 packages/client/src/runtime/utils/modelNameForTable.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import type { RuntimeDataModel } from '@prisma/client-common'

/**
* Maps a physical table name reported by a driver adapter back to the name of
* the Prisma model backed by that table, taking `@@map` and `@@schema` into
* account.
*
* The reported table may be schema-qualified (`<schema>.<table>`). When a table
* name is shared by more than one model in different database schemas, the
* models are disambiguated by the reported schema, provided the runtime data
* model carries per-model schema information (older generated clients and the
* pruned edge data model may not).
*
* Returns `undefined` when no model matches or when the match stays ambiguous
* (several models map to the reported table and the schema is not available to
* tell them apart), so that the caller can fall back to the top-level
* operation's model name instead of guessing.
*/
export function modelNameForTable(runtimeDataModel: RuntimeDataModel, table: string): string | undefined {
const { schema, name } = parseTableName(table)

const candidates = Object.entries(runtimeDataModel.models).filter(
([modelName, model]) => (model.dbName ?? modelName) === name,
)

if (candidates.length <= 1) {
return candidates[0]?.[0]
}

if (schema !== undefined) {
const schemaMatches = candidates.filter(([, model]) => model.schema === schema)
if (schemaMatches.length === 1) {
return schemaMatches[0][0]
}
}

return undefined
}

function parseTableName(table: string): { schema: string | undefined; name: string } {
const separatorIndex = table.lastIndexOf('.')
if (separatorIndex === -1) {
return { schema: undefined, name: table }
}
return { schema: table.slice(0, separatorIndex), name: table.slice(separatorIndex + 1) }
}
Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.