Review Codebase for Improper Prisma `where` Usage
Created by: deepakduggirala
Description:
We've identified a potential issue where undefined values in Prisma where conditions are causing unintended behavior. This can lead to queries returning unexpected results, including retrieving unintended records when a filter is missing.
Problem Explanation:
Current Behavior:
- If a value in the
whereclause isundefined, Prisma removes the entire condition instead of treating it asNULLor an ignored filter. - If a value is explicitly
null, Prisma correctly appliesWHERE key IS NULL.
Example of Unexpected Behavior:
const value = undefined;
const result = await prisma.user.findFirst({
where: { email: value }
});
What actually happens?
Prisma removes the where clause entirely, making the query equivalent to:
SELECT * FROM "User" LIMIT 1;
This could return any user, which is not the expected behavior.
const value = null;
const result = await prisma.user.findFirst({
where: { email: value }
});
What happens here?
Prisma translates it to:
SELECT * FROM "User" WHERE "email" IS NULL LIMIT 1;
This behaves as expected, returning only users with NULL emails.
Impact of This Issue:
-
Unexpected Query Behavior: If filters are dynamically set, unintended records may be retrieved if a value happens to be
undefined. - Security Risk: If critical filters are unintentionally removed, data exposure issues may arise.
- Logical Errors: If business logic assumes a filter is applied when it isn't, incorrect results may be used in application decisions.
Tasks:
-
Audit the codebase for all instances of
prisma.findFirst,findMany,findUnique,deleteMany, or any other query usingwhere. -
Ensure filters are correctly applied, using one of the following approaches:
-
Explicitly construct the
whereclause only if values are defined:const whereClause: any = {}; if (value !== undefined) whereClause.email = value; const result = await prisma.user.findFirst({ where: whereClause }); -
Use
?? nullto ensure Prisma doesn’t remove the condition:const result = await prisma.user.findFirst({ where: { email: value ?? null } });
-
Explicitly construct the
-
Write tests to ensure that undefined values do not cause Prisma to drop
whereconditions unexpectedly. - Document the best practice for handling optional filters in Prisma queries.
Priority: High
This issue could lead to incorrect data retrieval and security concerns. Fixing it ensures predictable query behavior across the application.