Last active
August 25, 2023 04:14
-
-
Save fahmifan/e34bbdbcd06577fc8db7ca018f04e822 to your computer and use it in GitHub Desktop.
How to log slow prisma query, tested on Prisma 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const prismaClient = new PrismaClient({ | |
log: ['query'] // must enable this to log | |
}); | |
// Log slow query with all parameters in place, | |
// so you can copy pasted it and do EXPLAIN query | |
prismaClient.$on('query' as any, (e: any) => { | |
const dur = Number.parseInt(e?.duration); | |
const maxQueryTime = 100; // in ms | |
if (dur <= maxQueryTime) return; | |
console.debug('PRISMA SLOW QUERY >>>', { | |
duration: dur, | |
query: replaceQuestionMarks(e?.query, e?.params) | |
}); | |
}); | |
function replaceQuestionMarks(query: string, args: string): string { | |
// add quotes to date | |
const queryParamsArray = args.replace(/(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} UTC)/g, (match) => { | |
return `"${match}"`; | |
}); | |
const paramObjs = JSON.parse(queryParamsArray); | |
let replacedQuery = query; | |
for (const arg of paramObjs) { | |
if (typeof arg === 'number') { | |
replacedQuery = replacedQuery.replace('?', `${arg}`); | |
continue; | |
} | |
replacedQuery = replacedQuery.replace('?', `'${arg}'`); | |
} | |
return replacedQuery; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment