Skip to content

fix(postgres): populate fields, value and reltype in ForeignKeyConstraintError#18129

Open
topmonroe9 wants to merge 1 commit intosequelize:mainfrom
topmonroe9:fix/postgres-fk-error-fields
Open

fix(postgres): populate fields, value and reltype in ForeignKeyConstraintError#18129
topmonroe9 wants to merge 1 commit intosequelize:mainfrom
topmonroe9:fix/postgres-fk-error-fields

Conversation

@topmonroe9
Copy link
Copy Markdown

@topmonroe9 topmonroe9 commented Feb 27, 2026

Summary

Closes #7826

The PostgreSQL dialect was hardcoding fields: null when constructing ForeignKeyConstraintError, even though err.detail contains the offending field names and values. This made it impossible for developers to build user-friendly error messages from FK constraint violations — a long-standing complaint on the issue.

Before:

{ table: 'users', fields: null, value: undefined, reltype: undefined }

After:

{ table: 'users', fields: ['user_id'], value: ['42'], reltype: 'child' }

Changes

  • packages/postgres/src/query.js — parse err.detail to extract FK field names and values via the Key (field)=(value) pattern already used for unique constraint errors (23505). Determine reltype from the error message (insert or update → child, update or delete → parent).
  • packages/core/test/integration/error.test.ts — update postgres assertions to expect populated fields and reltype

Test plan

  • Integration tests for FK constraint errors (need a running PG instance, verified via CI)
  • ESLint passes
  • Prettier passes

Summary by CodeRabbit

  • Bug Fixes
    • PostgreSQL foreign key constraint errors now provide enhanced diagnostics with richer error metadata. When constraint violations occur, error messages explicitly report the specific affected field names and constraint relationship type (parent or child relationships), providing clearer diagnostics to help identify and troubleshoot database integrity issues more effectively.

…raintError

Closes sequelize#7826

The PostgreSQL dialect was hardcoding `fields: null` in
ForeignKeyConstraintError even though the error detail string contains
the constraint fields and values. This made it impossible for users to
build meaningful error messages from FK violations.

Parse `err.detail` (e.g. `Key (user_id)=(42) is not present in table
"users"`) to extract field names and values, and determine the
relationship type from the error message.
@topmonroe9 topmonroe9 requested a review from a team as a code owner February 27, 2026 06:50
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Feb 27, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 70236a8 and fbd8655.

📒 Files selected for processing (2)
  • packages/core/test/integration/error.test.ts
  • packages/postgres/src/query.js

📝 Walkthrough

Walkthrough

The PR enhances PostgreSQL foreign key constraint error handling by extracting detailed metadata—including specific field names and relationship type (parent/child)—from database errors and including them in the ForeignKeyConstraintError, replacing previously null values.

Changes

Cohort / File(s) Summary
Error Handling Enhancement
packages/postgres/src/query.js
Updated PostgresQuery.formatError for code '23503' to extract foreign-key field details and relationship type from error metadata, constructing ForeignKeyConstraintError with fields, value, and reltype properties instead of null values.
Test Assertions
packages/core/test/integration/error.test.ts
Updated foreign key constraint error test assertions to validate that error.fields contains the specific constraint field arrays and error.reltype is correctly set to 'parent' or 'child'.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Suggested reviewers

  • sdepold
  • ephys

Poem

🐰 Hop, hop! The errors now whisper their secrets true,
Which fields caused the fuss, and parent/child clues too,
No more mysteries lurking in the null abyss,
PostgreSQL's details shine bright—what a bliss! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: populating fields, value, and reltype properties in ForeignKeyConstraintError for PostgreSQL.
Linked Issues check ✅ Passed The PR directly addresses issue #7826 by extracting FK field names and values from PostgreSQL error details and populating ForeignKeyConstraintError properties.
Out of Scope Changes check ✅ Passed All changes are scoped to fixing ForeignKeyConstraintError for PostgreSQL: error parsing in query.js and test assertions in error.test.ts.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 OpenGrep (1.16.1)
packages/core/test/integration/error.test.ts

┌──────────────┐
│ Opengrep CLI │
└──────────────┘

�[32m✔�[39m �[1mOpengrep OSS�[0m
�[32m✔�[39m Basic security coverage for first-party code vulnerabilities.

�[1m Loading rules from local config...�[0m

packages/postgres/src/query.js

┌──────────────┐
│ Opengrep CLI │
└──────────────┘

�[32m✔�[39m �[1mOpengrep OSS�[0m
�[32m✔�[39m Basic security coverage for first-party code vulnerabilities.

�[1m Loading rules from local config...�[0m


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@topmonroe9
Copy link
Copy Markdown
Author

topmonroe9 commented Feb 27, 2026

Looks like the db2 failure is in remove-column.test.ts (referencedColumnNames assertion) - not sure if it's a flaky test or a known thing, but it's definitely not related to this PR. The changes here only touch the postgres query handler and the error integration test.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Allow defining custom ForeignKeyConstraintError messages

1 participant