Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

fix(adapter-pg): validate database connection during connect#28925

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.

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

Already on GitHub?Sign in to your account

Open
CHOIJEWON wants to merge2 commits intoprisma:main
base:main
Choose a base branch
Loading
fromCHOIJEWON:fix/prisma-postgres-connection

Conversation

@CHOIJEWON
Copy link

@CHOIJEWONCHOIJEWON commentedDec 16, 2025
edited
Loading

Summary

Fixes#28896

This PR fixes issue#28896 where$connect() succeeds even when PostgreSQL is stopped when using@prisma/adapter-pg. The root cause was thatpg.Pool uses lazy connection initialization, so creating a pool doesn't actually establish a database connection until the first query is executed.

Problem

Before this fix:

constadapter=newPrismaPgAdapterFactory(config)awaitprisma.$connect()// ✅ Succeeds even when PostgreSQL is offlineawaitprisma.user.findMany()// ❌ Fails here with connection error

Expected behavior:

constadapter=newPrismaPgAdapterFactory(config)awaitprisma.$connect()// ❌ Should fail immediately if database is unreachable

Root Cause

ThePrismaPgAdapterFactory.connect() method only instantiatednew pg.Pool(config) without validating the connection. Sincepg.Pool uses lazy connection initialization, no actual connection attempt occurred until the first query execution, causing$connect() to succeed even when the database was offline.

Solution

Added avalidateConnection() private method that executesSELECT 1 during theconnect() phase to validate the database is reachable:

privateasyncvalidateConnection(pool:pg.Pool):Promise<void>{consttag='[js::validateConnection]'try{// SELECT 1 is the lightest query (best for connection validation)awaitpool.query('SELECT 1')debug(`${tag} Connection validated successfully`)}catch(e){debug(`${tag} Connection failed: %O`,e)throwe}}

This method is called inconnect() before returning the adapter, ensuring that any connection errors are surfaced immediately during$connect() rather than being deferred to the first query.

Changes Made

packages/adapter-pg/src/pg.ts:

  • AddedvalidateConnection() private method (lines 318-329)
  • CallvalidateConnection() inconnect() before returning adapter (line 284)

packages/adapter-pg/src/__tests__/pg.test.ts:

Testing

Regression Tests:

it('should throw an error when database is unreachable during connect',async()=>{constconfig:pg.PoolConfig={user:'test',password:'test',database:'test',host:'192.0.2.1',// TEST-NET-1 - reserved for documentation, guaranteed to be unreachableport:54321,connectionTimeoutMillis:100,}constfactory=newPrismaPgAdapterFactory(config)awaitexpect(factory.connect()).rejects.toThrow()})it('should throw an error when database connection fails with external pool',async()=>{constmockPool=newpg.Pool({...})mockPool.query=vi.fn().mockRejectedValue(newError('Connection refused'))constfactory=newPrismaPgAdapterFactory(mockPool)awaitexpect(factory.connect()).rejects.toThrow('Connection refused')awaitmockPool.end()})

Test Requirements:

  • Tests require Docker PostgreSQL to be running (postgres://prisma:prisma@localhost:5432/tests)
  • Matches Prisma's CI/CD testing pattern
  • Uses real database connections instead of mocks for integration testing

Behavior Changes

After this fix:

constadapter=newPrismaPgAdapterFactory(config)awaitprisma.$connect()// ❌ Now fails immediately if PostgreSQL is unreachable

This is the correct behavior and matches user expectations for connection validation.

Related Work

  • Similar validation pattern exists in@prisma/adapter-mariadb which usesSELECT VERSION() for capability detection
  • @prisma/adapter-neon has similar connection error handling tests

Breaking Changes

None. This is a bug fix that makes the behavior match documented expectations.


Additional Notes

The ECONNREFUSED error when Docker PostgreSQL is not running is expected and acceptable behavior - it confirms that the connection validation is working correctly and surfacing errors immediately during$connect() as intended.

Summary by CodeRabbit

  • New Features

    • Added stronger connection validation and error handling during adapter initialization to ensure the database is reachable.
  • Tests

    • Enhanced tests for connection failure scenarios, covering unreachable databases and simulated pool connection errors.

✏️ Tip: You can customize this high-level summary in your review settings.

@CLAassistant
Copy link

CLAassistant commentedDec 16, 2025
edited
Loading

CLA assistant check
All committers have signed the CLA.

@coderabbitai
Copy link
Contributor

coderabbitaibot commentedDec 16, 2025
edited
Loading

Walkthrough

Adds a connection validation step to PrismaPgAdapterFactory by runningSELECT 1 duringconnect(). Refactors tests to use a sharedtestConfig derived fromTEST_POSTGRES_URI and adds two tests for connection-failure scenarios. A duplicatevalidateConnection declaration appears in the diff.

Changes

Cohort / File(s)Summary
Tests: shared config & failure cases
packages/adapter-pg/src/__tests__/pg.test.ts
AddsgetTestConfig() helper to derivepg.PoolConfig fromTEST_POSTGRES_URI; replaces hardcoded pool configs withtestConfig; adds tests verifyingconnect() throws when DB is unreachable and when an externalPool fails to connect (mocked).
Connection validation in adapter
packages/adapter-pg/src/pg.ts
Adds a privateasync validateConnection(pool: pg.Pool): Promise<void> that runsSELECT 1 and throwsDriverAdapterError(convertDriverError(e)) on failure;connect() now awaitsvalidateConnection(client) before setting up idle error handling. Diff shows thevalidateConnection method declared twice.

Suggested labels

lgtm

Suggested reviewers

  • aqrln
  • jacek-prisma
  • jkomyno

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check nameStatusExplanation
Title check✅ PassedThe title accurately summarizes the main change: adding connection validation to the PostgreSQL adapter's connect method to ensure database connectivity is verified during $connect().
Docstring Coverage✅ PassedDocstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for usingCodeRabbit! 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.

Copy link
Contributor

@coderabbitaicoderabbitaibot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Actionable comments posted: 3

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between531886f and1fdc311.

📒 Files selected for processing (2)
  • packages/adapter-pg/src/__tests__/pg.test.ts (6 hunks)
  • packages/adapter-pg/src/pg.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx,js,jsx}: Use kebab-case for new file names (e.g.,query-utils.ts,filter-operators.test.ts)
Avoid creating barrel files (index.ts that re-export from other modules). Import directly from the source file (e.g.,import { foo } from './utils/query-utils' notimport { foo } from './utils'), unless./utils/index.ts file already exists

Files:

  • packages/adapter-pg/src/__tests__/pg.test.ts
  • packages/adapter-pg/src/pg.ts
**/*.test.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

Test files named*.test.ts are excluded from build output via esbuild config; place tests alongside source files

Files:

  • packages/adapter-pg/src/__tests__/pg.test.ts
🔇 Additional comments (2)
packages/adapter-pg/src/pg.ts (1)

281-303:LGTM! Connection validation ensures early failure detection.

The addition ofvalidateConnection(client) before setting up error handlers correctly addresses the lazy connection issue withpg.Pool. This ensures connection errors surface during$connect() rather than on first query.

packages/adapter-pg/src/__tests__/pg.test.ts (1)

113-127:LGTM! Good regression test for unreachable database.

Excellent use of the TEST-NET-1 reserved IP address (192.0.2.1) which is guaranteed to be unreachable, and short timeout for fast test execution. This correctly validates the fix for issue#28896.

…nd error handling  - Add explicit type guard for TEST_POSTGRES_URI instead of type assertion  - Use try-finally to ensure test resource cleanup  - Wrap validation errors in DriverAdapterError for consistenc
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment

Reviewers

@coderabbitaicoderabbitai[bot]coderabbitai[bot] left review comments

At least 1 approving review is required to merge this pull request.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

$connect() always succeeds in Prisma v7 using @prisma/adapter-pg even when DB is unreachable

2 participants

@CHOIJEWON@CLAassistant

[8]ページ先頭

©2009-2025 Movatter.jp