Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
b0c51c4
fix(adapter-neon): close a transaction at most once and reject statem…
wmadden-electric Nov 10, 2026
8db1f50
test(client-engine-runtime): cover statements sent while a transactio…
wmadden-electric Nov 10, 2026
a633156
fix(adapter-mariadb): close a transaction at most once and reject sta…
wmadden-electric Nov 10, 2026
d3175d6
fix(client-engine-runtime): stop statements from reaching a transacti…
wmadden-electric Nov 10, 2026
342fa93
docs(driver-adapter-utils): state that a transaction is closed once a…
wmadden-electric Nov 10, 2026
dcbbe95
docs(agents): describe the transaction handle getTransaction returns
wmadden-electric Nov 10, 2026
a2d80e5
test(client): rollback stops the remaining statements of a running cr…
wmadden-electric Nov 10, 2026
b2c99b4
refactor(client-engine-runtime): keep each nested transaction's savep…
wmadden-electric Nov 10, 2026
708da79
fix(client-engine-runtime): close a nested transaction before a rollb…
wmadden-electric Nov 10, 2026
5b97047
fix(client-engine-runtime): let the timeout and disconnect end a wait…
wmadden-electric Nov 10, 2026
49c8714
fix(adapter-mariadb): release a transaction's connection even when re…
wmadden-electric Nov 10, 2026
5ff7bc3
refactor(adapter-pg): name the transaction's close guard as adapter-n…
wmadden-electric Nov 10, 2026
c6fa221
docs(driver-adapter-utils): say that rollback may arrive while a stat…
wmadden-electric Nov 10, 2026
04cca56
docs(agents): describe nested commits and interrupted commits in the …
wmadden-electric Nov 10, 2026
3478445
test(client): roll back as soon as the first INSERT of the createMany…
wmadden-electric Nov 10, 2026
6a28f92
test(client): skip the createMany rollback test with the remote execu…
wmadden-electric Nov 10, 2026
d23f7af
fix(client-engine-runtime): make the enclosing transaction wait for s…
wmadden-electric Nov 10, 2026
7acfc13
refactor(adapter-pg): word the release error as adapter-neon does
wmadden-electric Nov 10, 2026
fb8a433
test(client): roll back during an update with a nested create instead…
wmadden-electric Nov 10, 2026
b3db931
test(client): give the rollback test's update a nested updateMany too
wmadden-electric Nov 10, 2026
5984b06
docs(driver-adapter-utils): say which Transaction calls may overlap a…
wmadden-electric Nov 11, 2026
2dc1ff4
fix(client-engine-runtime): report a rolled back nested transaction a…
wmadden-electric Nov 11, 2026
38d11bd
docs(client-engine-runtime): say a nested commit never closes a state…
wmadden-electric Nov 13, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,11 @@
- `QueryInterpreter` class in `packages/client-engine-runtime/src/interpreter/query-interpreter.ts` executes query plans against `SqlQueryable` (driver adapter interface).
- Query plans are cached and shared between requests (`QueryPlanCache` in `packages/client/src/runtime/core/engines/client/query-plan-cache.ts`), so the interpreter receives them as `DeepReadonly` and must never mutate them (#29262 fixed such a bug and added a functional regression test in `packages/client/tests/functional/issues/29254-query-plan-cache-mutation`). Code that needs a modified plan must copy the affected nodes; structural sharing of unaffected subtrees is fine (see `purifyQueryPlan`).
- Query flow: `PrismaClient` → `ClientEngine.request()` → query compiler → `executor.execute()` → `QueryInterpreter.run()` → driver adapter.
- Statement order inside one plan: `seq` and `let` run their children one after another, while `sum`, `concat` and `join` children run concurrently with `Promise.all`. A `createMany` too large for one statement compiles to one `execute` node per chunk under a `sum`, so all its INSERTs are sent at once. Nested writes (for example `update` with a nested `create`) compile to `let`/`seq`, so each statement is sent only after the previous one returned. Print a plan with `DEBUG=prisma:client:clientEngine` ("query plan created").
- `ExecutePlanParams` interface in `packages/client/src/runtime/core/engines/client/Executor.ts` defines what's passed through the execution chain.
- `TransactionManager` in `packages/client-engine-runtime/src/transaction-manager/transaction-manager.ts` owns interactive transaction IDs and implements nested transactions using savepoints. Savepoint SQL is provider-specific (e.g. PostgreSQL uses `ROLLBACK TO SAVEPOINT <name>`, MySQL/SQLite use `ROLLBACK TO <name>`, SQL Server uses `SAVE TRANSACTION <name>` / `ROLLBACK TRANSACTION <name>` and has no release statement).
- `Transaction` in `packages/driver-adapter-utils` models savepoint behavior as async methods (`createSavepoint`, `rollbackToSavepoint`, optional `releaseSavepoint`) instead of returning SQL via `savepoint(action, name)`. `TransactionManager` expects adapter methods for savepoints and does not synthesize provider fallback SQL.
- `TransactionManager.getTransaction()` returns a guarded `SqlQueryable`, not the adapter's `Transaction`. The handle belongs to the transaction or nested transaction that was innermost when it was issued, and rejects statements with the P2028 closed/rolled back/expired error once that level starts closing. A nested commit merges its level into the parent, so its handles keep working there; a nested rollback closes the level. Closing waits for statements already running (rollback, timeout and disconnect for at most 2 seconds; commit until they settle, unless the timeout or disconnect arrives first, which turns the commit into a rollback and rejects it with the matching P2028 error), then sends `COMMIT`/`ROLLBACK` through the adapter's `Transaction` directly.
- Fluent API `dataPath` is built in `packages/client/src/runtime/core/model/applyFluent.ts` by appending `['select', <relationName>]` on each hop; runtime unpacking in `packages/client/src/runtime/RequestHandler.ts` currently strips `'select'`/`'include'` segments before `deepGet`.
- In extension context resolution, `dataPath` should be interpreted as selector/field pairs (`select|include`, relation field). Do not strip by raw string value or relation fields literally named `select`/`include` get dropped.

Expand Down
100 changes: 100 additions & 0 deletions packages/adapter-mariadb/src/mariadb.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,106 @@ describe('transaction connection management', () => {
expect(conn.listenerCount('error')).toBe(0)
})

function startTransactionOn(conn: ReturnType<typeof makePoolConn>) {
const pool = {
getConnection: vi.fn().mockResolvedValue(conn),
query: vi.fn().mockResolvedValue([['8.0.13']]),
} as unknown as mariadb.Pool
return new PrismaMariaDbAdapter(pool, { supportsRelationJoins: false }).startTransaction()
}

const closed = { name: 'DriverAdapterError', cause: { kind: 'TransactionAlreadyClosed' } }

test.each(['commit', 'rollback'] as const)(
'a second close after %s sends no SQL and does not release the connection again',
async (first) => {
const conn = makePoolConn()
const tx = await startTransactionOn(conn)

await tx[first]()
conn.query.mockClear()
await tx.commit()
await tx.rollback()

expect(conn.query).not.toHaveBeenCalled()
expect(conn.release).toHaveBeenCalledTimes(1)
},
)

test('a close or statement issued while COMMIT is running sends no SQL', async () => {
const conn = makePoolConn()
let finishCommit!: () => void
conn.query.mockImplementation(({ sql }: { sql: string }) =>
sql === 'COMMIT' ? new Promise<void>((resolve) => (finishCommit = resolve)) : Promise.resolve([]),
)
const tx = await startTransactionOn(conn)

const commit = tx.commit()
await tx.rollback()
await expect(tx.executeRaw({ sql: 'SELECT 1', args: [], argTypes: [] })).rejects.toMatchObject(closed)
finishCommit()
await commit

expect(conn.query.mock.calls.map(([{ sql }]) => sql)).toEqual(['BEGIN', 'COMMIT'])
expect(conn.execute).not.toHaveBeenCalled()
expect(conn.release).toHaveBeenCalledTimes(1)
})

test.each([
['commit', 'COMMIT'],
['rollback', 'ROLLBACK'],
] as const)('a failing %s surfaces the error and releases the connection once', async (close, sql) => {
const conn = makePoolConn()
const tx = await startTransactionOn(conn)
const lostConnection = Object.assign(new Error('Lost connection'), {
errno: 2013,
sqlMessage: 'Lost connection to server during query',
sqlState: 'HY000',
})
conn.query.mockImplementation(({ sql: sent }: { sql: string }) =>
sent === sql ? Promise.reject(lostConnection) : Promise.resolve([]),
)

await expect(tx[close]()).rejects.toMatchObject({
name: 'DriverAdapterError',
cause: { originalCode: '2013', originalMessage: 'Lost connection to server during query' },
})
conn.query.mockClear()
await tx.commit()
await tx.rollback()

expect(conn.query).not.toHaveBeenCalled()
expect(conn.release).toHaveBeenCalledTimes(1)
})

test('the connection is released even when removing the error listener throws', async () => {
const conn = makePoolConn()
const tx = await startTransactionOn(conn)
vi.spyOn(conn, 'off').mockImplementationOnce(() => {
throw new Error('off failed')
})

await expect(tx.commit()).rejects.toThrow('off failed')

expect(conn.release).toHaveBeenCalledTimes(1)
})

test('statements and savepoint calls after close are rejected without reaching the driver', async () => {
const conn = makePoolConn()
const tx = await startTransactionOn(conn)

await tx.rollback()
conn.query.mockClear()

await expect(tx.executeRaw({ sql: 'SELECT 1', args: [], argTypes: [] })).rejects.toMatchObject(closed)
await expect(tx.queryRaw({ sql: 'SELECT 1', args: [], argTypes: [] })).rejects.toMatchObject(closed)
await expect(tx.createSavepoint!('sp')).rejects.toMatchObject(closed)
await expect(tx.rollbackToSavepoint!('sp')).rejects.toMatchObject(closed)
await expect(tx.releaseSavepoint!('sp')).rejects.toMatchObject(closed)
expect(conn.query).not.toHaveBeenCalled()
expect(conn.execute).not.toHaveBeenCalled()
})

test('falls back to end() for non-pool connections (no release method)', async () => {
const conn = makePoolConn()
const connNoRelease = { ...conn, release: undefined as unknown as typeof conn.release }
Expand Down
70 changes: 51 additions & 19 deletions packages/adapter-mariadb/src/mariadb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,14 @@ class MariaDbQueryable<Connection extends mariadb.Pool | mariadb.Connection> imp
// All transaction operations use `client.query` instead of `client.execute` to avoid using the
// binary protocol, which does not support transactions in the MariaDB driver.
class MariaDbTransaction extends MariaDbQueryable<mariadb.Connection> implements Transaction {
/**
* Set on entry to `commit()` or `rollback()`, before either sends SQL. Once the pool has lent the
* connection to a new owner, a second close would send `COMMIT` or `ROLLBACK` into that owner's
* session and release the connection twice, so the transaction closes at most once and sends
* nothing afterwards.
*/
private closed = false

constructor(
readonly conn: mariadb.Connection,
mariadbOptions: PrismaMariadbOptions | undefined,
Expand All @@ -94,42 +102,66 @@ class MariaDbTransaction extends MariaDbQueryable<mariadb.Connection> implements
super(conn, mariadbOptions)
}

protected override async performIO(query: SqlQuery): Promise<ArrayModeResult> {
this.assertOpen()
return await super.performIO(query)
}

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

try {
await this.client.query({ sql: 'COMMIT' })
} catch (err) {
this.onError(err)
} finally {
this.cleanup?.()
await releaseConnection(this.client)
}
await this.close('COMMIT')
}

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

try {
await this.client.query({ sql: 'ROLLBACK' })
} catch (err) {
this.onError(err)
} finally {
this.cleanup?.()
await releaseConnection(this.client)
}
await this.close('ROLLBACK')
}

async createSavepoint(name: string): Promise<void> {
await this.client.query({ sql: `SAVEPOINT ${name}` }).catch(this.onError.bind(this))
await this.sendTransactionControl(`SAVEPOINT ${name}`)
}

async rollbackToSavepoint(name: string): Promise<void> {
await this.client.query({ sql: `ROLLBACK TO ${name}` }).catch(this.onError.bind(this))
await this.sendTransactionControl(`ROLLBACK TO ${name}`)
}

async releaseSavepoint(name: string): Promise<void> {
await this.client.query({ sql: `RELEASE SAVEPOINT ${name}` }).catch(this.onError.bind(this))
await this.sendTransactionControl(`RELEASE SAVEPOINT ${name}`)
}

private async close(sql: 'COMMIT' | 'ROLLBACK'): Promise<void> {
if (this.closed) {
return
}
this.closed = true

try {
await this.client.query({ sql })
} catch (err) {
this.onError(err)
} finally {
try {
this.cleanup?.()
} finally {
await releaseConnection(this.client)
}
}
}

private async sendTransactionControl(sql: string): Promise<void> {
this.assertOpen()
await this.client.query({ sql }).catch(this.onError.bind(this))
}

private assertOpen(): void {
if (this.closed) {
throw new DriverAdapterError({
kind: 'TransactionAlreadyClosed',
cause: 'The transaction has already been committed or rolled back',
})
}
}
}

Expand Down
114 changes: 113 additions & 1 deletion packages/adapter-neon/src/__tests__/neon.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as neon from '@neondatabase/serverless'
import { getLogs } from '@prisma/debug'
import type { SqlQuery } from '@prisma/driver-adapter-utils'
import { describe, expect, it, vi } from 'vitest'
import { afterEach, describe, expect, it, vi } from 'vitest'

import { PrismaNeonAdapterFactory, PrismaNeonHttpAdapter } from '../neon'

Expand Down Expand Up @@ -78,6 +78,118 @@ describe('PrismaNeonAdapterFactory', () => {
})
})

describe('NeonTransaction', () => {
// Regression tests for https://github.com/prisma/prisma/issues/29952: closing a
// transaction twice must not release the pooled client twice, and no SQL may be
// sent on a client the pool may have lent to someone else.
//
// No database is needed: neon.Client's connect/query/end are stubbed, and the
// real neon.Pool manages the clients.

const statements: string[] = []
const pools: neon.Pool[] = []

afterEach(async () => {
await Promise.all(pools.map((pool) => pool.end()))
pools.length = 0
vi.restoreAllMocks()
})

async function setup(queryImpl?: (text: string) => Promise<unknown> | undefined) {
statements.length = 0

vi.spyOn(neon.Client.prototype, 'connect').mockImplementation(function (cb?: (err?: Error) => void) {
process.nextTick(() => cb?.())
} as never)
vi.spyOn(neon.Client.prototype, 'end').mockImplementation((() => Promise.resolve()) as never)
vi.spyOn(neon.Client.prototype, 'query').mockImplementation(((query: string | { text: string }) => {
const text = typeof query === 'string' ? query : query.text
statements.push(text)
return queryImpl?.(text) ?? Promise.resolve({ rowCount: 0, rows: [], fields: [] })
}) as never)

const adapter = await new PrismaNeonAdapterFactory({
connectionString: 'postgresql://user:pass@localhost:5432/db',
max: 1,
}).connect()
const pool = adapter.underlyingDriver()
pools.push(pool)
const releases: unknown[] = []
pool.on('release', (err) => releases.push(err))

return { pool, adapter, releases }
}

it('should treat a second close as a no-op instead of releasing twice', async () => {
const { pool, adapter, releases } = await setup()
const tx = await adapter.startTransaction()

await tx.commit()
await expect(tx.rollback()).resolves.toBeUndefined()

expect(releases).toEqual([undefined])
expect(pool.idleCount).toBe(1)
expect(pool.totalCount).toBe(1)
})

it('should not release a client the pool has lent to a new owner', async () => {
const { pool, adapter } = await setup()
const tx = await adapter.startTransaction()

await tx.rollback()
const nextOwner = await pool.connect()
await tx.commit()

expect(() => nextOwner.release()).not.toThrow()
expect(pool.idleCount).toBe(1)
expect(pool.totalCount).toBe(1)
})

it('should reject statements and savepoint calls after close without sending SQL', async () => {
const { adapter } = await setup()
const tx = await adapter.startTransaction()

await tx.rollback()
statements.length = 0

const closed = { name: 'DriverAdapterError', cause: { kind: 'TransactionAlreadyClosed' } }
await expect(tx.executeRaw({ sql: 'ROLLBACK', args: [], argTypes: [] })).rejects.toMatchObject(closed)
await expect(tx.queryRaw({ sql: 'SELECT 1', args: [], argTypes: [] })).rejects.toMatchObject(closed)
await expect(tx.createSavepoint!('sp')).rejects.toMatchObject(closed)
await expect(tx.rollbackToSavepoint!('sp')).rejects.toMatchObject(closed)
await expect(tx.releaseSavepoint!('sp')).rejects.toMatchObject(closed)
expect(statements).toEqual([])
})

it('should destroy the connection when closing with a statement still running', async () => {
const { pool, adapter, releases } = await setup((text) =>
text === 'SELECT pending' ? new Promise(() => {}) : undefined,
)
const tx = await adapter.startTransaction()

void tx.executeRaw({ sql: 'SELECT pending', args: [], argTypes: [] })
await tx.rollback()

expect(releases).toEqual([expect.any(Error)])
expect(pool.totalCount).toBe(0)
})

it('should release the client even when removing the error listener throws', async () => {
const { pool, adapter, releases } = await setup()
const acquired: neon.PoolClient[] = []
pool.once('acquire', (client) => acquired.push(client))
const tx = await adapter.startTransaction()
vi.spyOn(acquired[0], 'removeListener').mockImplementationOnce(() => {
throw new Error('removeListener failed')
})

await expect(tx.commit()).rejects.toThrow('removeListener failed')

expect(releases).toEqual([undefined])
expect(pool.idleCount).toBe(1)
})
})

describe('PrismaNeonHttpAdapter', () => {
it('maps args through mapArg before passing them to the HTTP client', async () => {
const mockClient = vi.fn().mockResolvedValue({ fields: [], rows: [], rowCount: 0 })
Expand Down
Loading
Loading