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(adapter-pg): serialize queries within a transaction by matingathani · Pull Request #29468 · prisma/orm

fix(adapter-pg): serialize queries within a transaction #29468

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

Open
matingathani wants to merge 7 commits into prisma:v7
base: v7
Loading
Loading
from matingathani:fix/adapter-pg-concurrent-transaction-queries

Uh oh!

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

Open

fix(adapter-pg): serialize queries within a transaction #29468

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
7 commits
Select commit Hold shift + click to select a range
fb6172d
fix(client-engine-runtime): serialize join children inside transactions
matingathani Apr 15, 2026
f7ee940
fix(adapter-pg): serialize concurrent transaction queries with a mutex
matingathani Apr 16, 2026
0be9563
refactor(adapter-pg): simplify mutex to runExclusive per CodeRabbit
matingathani Apr 17, 2026
91de396
Merge remote-tracking branch 'origin/main' into fix/adapter-pg-concur…
tensordreams Jul 22, 2026
91ab990
test(adapter-pg): cover transaction query serialization and mutex rel…
tensordreams Jul 23, 2026
9eeb744
Merge remote-tracking branch 'origin/main' into fix/adapter-pg-concur…
tensordreams Jul 23, 2026
0f4ad1d
chore(adapter-pg): add async-mutex to lockfile
tensordreams Jul 23, 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

There are no files selected for viewing

1 change: 1 addition & 0 deletions 1 packages/adapter-pg/package.json
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"sideEffects": false,
"dependencies": {
"@prisma/driver-adapter-utils": "workspace:*",
"async-mutex": "0.5.0",
"pg": "^8.16.3",
"postgres-array": "3.0.4",
"@types/pg": "^8.16.0"
Expand Down
58 changes: 58 additions & 0 deletions 58 packages/adapter-pg/src/__tests__/pg.test.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,64 @@ describe('PrismaPgAdapterFactory', () => {
await adapter.dispose()
})

it('should serialize concurrent queries within a transaction', async () => {
const config: pg.PoolConfig = { user: 'test', password: 'test', database: 'test', port: 5432, host: 'localhost' }
const factory = new PrismaPgAdapterFactory(config)
const adapter = await factory.connect()

let inFlight = 0
let maxInFlight = 0
const mockConnection = {
on: vi.fn(),
removeListener: vi.fn(),
query: vi.fn(async () => {
inFlight++
maxInFlight = Math.max(maxInFlight, inFlight)
await new Promise((resolve) => setTimeout(resolve, 10))
inFlight--
return { rows: [], fields: [], rowCount: 0 }
}),
release: vi.fn(),
listenerCount: vi.fn().mockReturnValue(0),
}
adapter['client'].connect = vi.fn().mockResolvedValue(mockConnection)

const transaction = await adapter.startTransaction()
const query: SqlQuery = { sql: 'SELECT 1', args: [], argTypes: [] }
await Promise.all([transaction.queryRaw(query), transaction.queryRaw(query), transaction.queryRaw(query)])

expect(maxInFlight).toBe(1)
expect(mockConnection.query).toHaveBeenCalledTimes(4) // BEGIN + 3 queries

await transaction.commit()
await adapter.dispose()
})

it('should release the transaction mutex when a query fails', async () => {
const config: pg.PoolConfig = { user: 'test', password: 'test', database: 'test', port: 5432, host: 'localhost' }
const factory = new PrismaPgAdapterFactory(config)
const adapter = await factory.connect()

const mockConnection = {
on: vi.fn(),
removeListener: vi.fn(),
query: vi.fn().mockResolvedValue({ rows: [], fields: [], rowCount: 0 }),
release: vi.fn(),
listenerCount: vi.fn().mockReturnValue(0),
}
adapter['client'].connect = vi.fn().mockResolvedValue(mockConnection)

const transaction = await adapter.startTransaction()
mockConnection.query.mockRejectedValueOnce(new Error('boom'))

const query: SqlQuery = { sql: 'SELECT 1', args: [], argTypes: [] }
await expect(transaction.queryRaw(query)).rejects.toThrow()
await expect(transaction.queryRaw(query)).resolves.toBeDefined()

await transaction.rollback()
await adapter.dispose()
})

it('should not pass name when statement name generator is not provided', async () => {
const factory = new PrismaPgAdapterFactory('postgresql://test:test@localhost/test')
const adapter = await factory.connect()
Expand Down
11 changes: 10 additions & 1 deletion 11 packages/adapter-pg/src/pg.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import type {
TransactionOptions,
} from '@prisma/driver-adapter-utils'
import { Debug, DriverAdapterError } from '@prisma/driver-adapter-utils'
import { Mutex } from 'async-mutex'
// @ts-ignore: this is used to avoid the `Module '"<path>/node_modules/@types/pg/index"' has no default export.` error.
import pg from 'pg'

Expand Down Expand Up @@ -98,7 +99,7 @@ class PgQueryable<ClientT extends StdClient | TransactionClient> implements SqlQ
* Should the query fail due to a connection error, the connection is
* marked as unhealthy.
*/
private async performIO(query: SqlQuery): Promise<pg.QueryArrayResult<any>> {
protected async performIO(query: SqlQuery): Promise<pg.QueryArrayResult<any>> {
const { sql, args } = query
const values = args.map((arg, i) => mapArg(arg, query.argTypes[i]))

Expand Down Expand Up @@ -132,6 +133,10 @@ class PgQueryable<ClientT extends StdClient | TransactionClient> implements SqlQ
}

class PgTransaction extends PgQueryable<TransactionClient> implements Transaction {
// pg.PoolClient does not support concurrent queries on the same connection,
// so we serialize all performIO calls with a mutex.
#mutex = new Mutex()
Comment thread
Comment on lines +136 to +138

@aqrln aqrln Jul 28, 2026

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

I think we should move the mutex to the base PgQueryable and do the serialization logic there instead of overriding performIO here.

As the comment says, pg.PoolClient doesn't allow this generally, doesn't matter if it's within a transaction or not. Batch transactions are just how you happen to be able to observe the issue right now in practice but the issue is more general.

Sorry, something went wrong.

Uh oh!

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

All reactions

constructor(
client: pg.PoolClient,
readonly options: TransactionOptions,
Expand All @@ -141,6 +146,10 @@ class PgTransaction extends PgQueryable<TransactionClient> implements Transactio
super(client, pgOptions)
}

protected async performIO(query: SqlQuery): Promise<pg.QueryArrayResult<any>> {
return this.#mutex.runExclusive(() => super.performIO(query))
}

async commit(): Promise<void> {
debug(`[js::commit]`)

Expand Down
3 changes: 3 additions & 0 deletions 3 pnpm-lock.yaml
Show comments
View file
Open in desktop

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Oops, something went wrong.

Uh oh!

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

Loading
Oops, something went wrong.

Uh oh!

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

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.