Skip to content

Commit

Permalink
driver-adapters: Ensure error propogation works for startTransaction (
Browse files Browse the repository at this point in the history
#4267)

* driver-adapters: Ensure error propohation works for `startTransaction`

`startTransaction` was not correctly wrapped when converting `Adapter`
to `ErrorCapturingAdapter`. As a result, `GenericError` message was
returned in case of JS error. This PR fixes the problem.

Since it is hard to test those kinds of errors with real drivers, new
test suite for the error propogation is introduced. It uses fake
postgres adapter that throws on every call.

* Add test for executeRaw
  • Loading branch information
Serhii Tatarintsev authored Sep 21, 2023
1 parent 0872812 commit 5a6164f
Show file tree
Hide file tree
Showing 6 changed files with 546 additions and 457 deletions.
25 changes: 18 additions & 7 deletions query-engine/driver-adapters/js/driver-adapter-utils/src/binder.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import type { ErrorCapturingDriverAdapter, DriverAdapter, Transaction, ErrorRegistry, ErrorRecord, Result } from './types'
import type {
ErrorCapturingDriverAdapter,
DriverAdapter,
Transaction,
ErrorRegistry,
ErrorRecord,
Result,
} from './types'

class ErrorRegistryInternal implements ErrorRegistry {
private registeredErrors: ErrorRecord[] = []
Expand All @@ -22,36 +29,40 @@ class ErrorRegistryInternal implements ErrorRegistry {
export const bindAdapter = (adapter: DriverAdapter): ErrorCapturingDriverAdapter => {
const errorRegistry = new ErrorRegistryInternal()

const startTransaction = wrapAsync(errorRegistry, adapter.startTransaction.bind(adapter))
return {
errorRegistry,
queryRaw: wrapAsync(errorRegistry, adapter.queryRaw.bind(adapter)),
executeRaw: wrapAsync(errorRegistry, adapter.executeRaw.bind(adapter)),
flavour: adapter.flavour,
startTransaction: async (...args) => {
const result = await adapter.startTransaction(...args)
const result = await startTransaction(...args)
if (result.ok) {
return { ok: true, value: bindTransaction(errorRegistry, result.value) }
}
return result
},
close: wrapAsync(errorRegistry, adapter.close.bind(adapter))
close: wrapAsync(errorRegistry, adapter.close.bind(adapter)),
}
}

// *.bind(transaction) is required to preserve the `this` context of functions whose
// execution is delegated to napi.rs.
const bindTransaction = (errorRegistry: ErrorRegistryInternal, transaction: Transaction): Transaction => {
return ({
return {
flavour: transaction.flavour,
options: transaction.options,
queryRaw: wrapAsync(errorRegistry, transaction.queryRaw.bind(transaction)),
executeRaw: wrapAsync(errorRegistry, transaction.executeRaw.bind(transaction)),
commit: wrapAsync(errorRegistry, transaction.commit.bind(transaction)),
rollback: wrapAsync(errorRegistry, transaction.rollback.bind(transaction)),
});
}
}

function wrapAsync<A extends unknown[], R>(registry: ErrorRegistryInternal, fn: (...args: A) => Promise<Result<R>>): (...args: A) => Promise<Result<R>> {
function wrapAsync<A extends unknown[], R>(
registry: ErrorRegistryInternal,
fn: (...args: A) => Promise<Result<R>>,
): (...args: A) => Promise<Result<R>> {
return async (...args) => {
try {
return await fn(...args)
Expand All @@ -60,4 +71,4 @@ function wrapAsync<A extends unknown[], R>(registry: ErrorRegistryInternal, fn:
return { ok: false, error: { kind: 'GenericJsError', id } }
}
}
}
}
1 change: 1 addition & 0 deletions query-engine/driver-adapters/js/smoke-test-js/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"pg:libquery": "cross-env-shell DATABASE_URL=\"${JS_PG_DATABASE_URL}\" node --test --loader=tsx ./src/libquery/pg.test.ts",
"pg:client": "DATABASE_URL=\"${JS_PG_DATABASE_URL}\" node --test --loader=tsx ./src/client/pg.test.ts",
"pg": "pnpm pg:libquery && pnpm pg:client",
"errors": "DATABASE_URL=\"${JS_PG_DATABASE_URL}\" node --test --loader=tsx ./src/libquery/errors.test.ts",
"prisma:planetscale": "cross-env-shell DATABASE_URL=\"${JS_PLANETSCALE_DATABASE_URL}\" \"pnpm prisma:db:push:mysql && pnpm prisma:db:execute:mysql\"",
"studio:planetscale": "cross-env-shell DATABASE_URL=\"${JS_PLANETSCALE_DATABASE_URL}\" \"pnpm prisma:studio:mysql\"",
"planetscale:libquery": "DATABASE_URL=\"${JS_PLANETSCALE_DATABASE_URL}\" node --test --loader=tsx ./src/libquery/planetscale.test.ts",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,8 @@ model Product {
properties Json
properties_null Json?
}

model User {
id String @id @default(uuid())
email String
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { bindAdapter } from '@prisma/driver-adapter-utils'
import test, { after, before, describe } from 'node:test'
import { createQueryFn, initQueryEngine, throwAdapterError } from './util'
import assert from 'node:assert'

const fakeAdapter = bindAdapter({
flavour: 'postgres',
startTransaction() {
throw new Error('Error in startTransaction')
},

queryRaw() {
throw new Error('Error in queryRaw')
},

executeRaw() {
throw new Error('Error in executeRaw')
},
close() {
return Promise.resolve({ ok: true, value: undefined })
},
})

const engine = initQueryEngine(fakeAdapter, '../../prisma/postgres/schema.prisma')
const doQuery = createQueryFn(engine, fakeAdapter)

const startTransaction = async () => {
const args = { isolation_level: 'Serializable', max_wait: 5000, timeout: 15000 }
const res = JSON.parse(await engine.startTransaction(JSON.stringify(args), '{}'))
if (res['error_code']) {
throwAdapterError(res, fakeAdapter)
}
}

describe('errors propagation', () => {
before(async () => {
await engine.connect('{}')
})
after(async () => {
await engine.disconnect('{}')
})

test('works for queries', async () => {
await assert.rejects(
doQuery({
modelName: 'Product',
action: 'findMany',
query: {
arguments: {},
selection: {
$scalars: true,
},
},
}),
/Error in queryRaw/,
)
})

test('works for executeRaw', async () => {
await assert.rejects(
doQuery({
action: 'executeRaw',
query: {
arguments: {
query: 'SELECT 1',
parameters: '[]',
},
selection: {
$scalars: true,
},
},
}),
/Error in executeRaw/,
)
})

test('works with implicit transaction', async () => {
await assert.rejects(
doQuery({
modelName: 'Product',
action: 'deleteMany',
query: {
arguments: {},
selection: {
$scalars: true,
},
},
}),
/Error in startTransaction/,
)
})

test('works with explicit transaction', async () => {
await assert.rejects(startTransaction(), /Error in startTransaction/)
})
})
Loading

0 comments on commit 5a6164f

Please sign in to comment.