Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
11 changes: 8 additions & 3 deletions packages/drizzle/src/transactions/beginTransaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export const beginTransaction: BeginTransaction = async function beginTransactio
let transaction: DrizzleTransaction

let transactionReady: () => void
let transactionFailed: (err: unknown) => void

// Await initialization here
// Prevent race conditions where the adapter may be
Expand Down Expand Up @@ -44,13 +45,17 @@ export const beginTransaction: BeginTransaction = async function beginTransactio
transactionReady()
})
}, options || this.transactionOptions)
.catch(() => {
// swallow
.catch((err) => {
// Connection failed before callback ran - reject instead of hanging forever
transactionFailed(err)
})

// Need to wait until the transaction is ready
// before binding its `resolve` and `reject` methods below
await new Promise<void>((resolve) => (transactionReady = resolve))
await new Promise<void>((res, rej) => {
transactionReady = res
transactionFailed = rej
})

this.sessions[id] = {
db: transaction,
Expand Down
43 changes: 43 additions & 0 deletions test/database/int.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2321,6 +2321,49 @@ describe('database', () => {
})
}

it(
Comment thread
AlessioGr marked this conversation as resolved.
'should throw error when beginTransaction fails to connect (drizzle)',
{ db: (adapter) => adapter.startsWith('postgres') || adapter === 'supabase' },
async () => {
const db = payload.db as unknown as Record<string, unknown>
const originalDrizzle = db.drizzle
try {
db.drizzle = {
transaction: () => Promise.reject(new Error('connection refused')),
}

await expect(() => payload.db.beginTransaction()).rejects.toThrow(/connection refused/)
} finally {
db.drizzle = originalDrizzle
}
},
)

it(
'should throw error when beginTransaction fails to connect (mongo)',
Comment thread
AlessioGr marked this conversation as resolved.
{
db: (adapter) =>
adapter === 'mongodb' || adapter === 'mongodb-atlas' || adapter === 'documentdb',
},
async () => {
const db = payload.db as unknown as Record<string, unknown>
const originalConnection = db.connection
try {
db.connection = {
getClient: () => ({
startSession: () => {
throw new Error('connection refused')
},
}),
}

await expect(() => payload.db.beginTransaction()).rejects.toThrow(/connection refused/)
} finally {
db.connection = originalConnection
}
},
)

describe('disableTransaction', () => {
let disabledTransactionPost
beforeAll(async () => {
Expand Down
Loading