P
Prisma2mo ago
orta

$use replacement for tracking prisma calls per request

Hey folks, I spotted that $use is getting deprecated, and wondered if anyone has an alternative method for keeping track of the number of prisma calls which happen in a single request?
1 Reply
orta
ortaOP2mo ago
The code is not particularly novel, but it does a good job of offering a scale for how many db roundtrips we make
import { Plugin } from "@envelop/core"
import { Prisma, PrismaClient } from "@prisma/client"

const TRACE_QUERIES = process.env.PRISMA_TRACE_QUERIES === "true"

let ticker = (_: Prisma.MiddlewareParams) => {}

export const prismaCounterSetup = (db: PrismaClient) => {
db.$use(async (params, next) => {
const result = await next(params)
ticker(params)
return result
})
}

export const prismaCounterPlugin = (): Plugin<any> => {
let count = 0
let modelCount: Record<string, number> = {}
return {
onExecute(e) {
count = 0
modelCount = {}
ticker = (p: Prisma.MiddlewareParams) => {
count++

// Useful to see where a query is being called from
TRACE_QUERIES && console.trace(e.args.operationName, p.model, p.action, p.args)

if (p.model) modelCount[p.model] = (modelCount[p.model] || 0) + 1
}
return {
onExecuteDone: (e) => {
if (count > 5) {
console.log(`${e.args.operationName} took ${count} db queries: ${JSON.stringify(modelCount)}`)
}
e.setResult({
...e.result,
extensions: { ...(e.result as any).extensions, dbQueries: count, modelCount },
})
},
}
},
}
}
import { Plugin } from "@envelop/core"
import { Prisma, PrismaClient } from "@prisma/client"

const TRACE_QUERIES = process.env.PRISMA_TRACE_QUERIES === "true"

let ticker = (_: Prisma.MiddlewareParams) => {}

export const prismaCounterSetup = (db: PrismaClient) => {
db.$use(async (params, next) => {
const result = await next(params)
ticker(params)
return result
})
}

export const prismaCounterPlugin = (): Plugin<any> => {
let count = 0
let modelCount: Record<string, number> = {}
return {
onExecute(e) {
count = 0
modelCount = {}
ticker = (p: Prisma.MiddlewareParams) => {
count++

// Useful to see where a query is being called from
TRACE_QUERIES && console.trace(e.args.operationName, p.model, p.action, p.args)

if (p.model) modelCount[p.model] = (modelCount[p.model] || 0) + 1
}
return {
onExecuteDone: (e) => {
if (count > 5) {
console.log(`${e.args.operationName} took ${count} db queries: ${JSON.stringify(modelCount)}`)
}
e.setResult({
...e.result,
extensions: { ...(e.result as any).extensions, dbQueries: count, modelCount },
})
},
}
},
}
}
The new metrics system, seems to largely be systems wide and not tell you which area of the code is hitting N^ problems So, maybe I need to build a light version of the opentelemetry tracer instead
Want results from more Discord servers?
Add your server