Skip to content
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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expose replicas as $replica() #21

Merged
merged 2 commits into from
Oct 25, 2023
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
22 changes: 20 additions & 2 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,26 @@ export const readReplicas = (options: ReplicasOptions, configureReplicaClient?:

return client.$extends({
client: {
$primary<T>(this: T): Omit<T, '$primary'> {
return client as unknown as Omit<T, '$primary'>
$primary<T extends object>(this: T): Omit<T, '$primary' | '$replica'> {
const context = Prisma.getExtensionContext(this)
// If we're in a transaction, the current client is connected to the
// primary.
if (!('$transaction' in context && typeof context.$transaction === 'function')) {
return context
}

return client as unknown as Omit<T, '$primary' | '$replica'>
},

$replica<T extends object>(this: T): Omit<T, '$primary' | '$replica'> {
const context = Prisma.getExtensionContext(this)
// If we're in a transaction, the current client is connected to the
// primary.
if (!('$transaction' in context && typeof context.$transaction === 'function')) {
throw new Error(`Cannot use $replica inside of a transaction`)
}

return replicaManager.pickReplica() as unknown as Omit<T, '$primary' | '$replica'>
},

async $connect() {
Expand Down
20 changes: 20 additions & 0 deletions tests/extension.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,26 @@ test('write query is executed against primary', async () => {
expect(logs).toEqual([{ server: 'primary', operation: 'updateMany' }])
})

test('$executeRaw and $executeRawUnsafe are executed against primary', async () => {
await prisma.$executeRaw`SELECT 1;`
await prisma.$executeRawUnsafe('SELECT $1 as id;', 1)

expect(logs).toEqual([
{ server: 'primary', operation: '$executeRaw' },
{ server: 'primary', operation: '$executeRawUnsafe' },
])
})

test('$executeRaw and $executeRawUnsafe are executed against replica if $replica() is used', async () => {
await prisma.$replica().$executeRaw`SELECT 1;`
await prisma.$replica().$executeRawUnsafe('SELECT $1 as id;', 1)

expect(logs).toEqual([
{ server: 'replica', operation: '$executeRaw' },
{ server: 'replica', operation: '$executeRawUnsafe' },
])
})

test('read query is executed against primary if $primary() is used', async () => {
await prisma.$primary().user.findMany()

Expand Down