prisma icon indicating copy to clipboard operation
prisma copied to clipboard

MySQL: findMany with null relational where clause generating incorrect query

Open alexghenderson opened this issue 4 years ago • 3 comments

Bug description

Attempting to use the where field on findMany with a null relational value is generating an incorrect query, resulting in zero rows.

Running this query with the schema defined below:

const user: string = "some-user"
const group: string | undefined = undefined;

db.transactionCategory.findMany({
  where: {
    user: user,
    categoryGroup: group ? { group } : null, // or group ? { group} : { is: null } -> same result
  },
  include: {
    categoryGroup: true,
    transaction: {
      include: {
        flags: true,
        account: true,
      },
    },
  },
})

Results in this query:

SELECT 
	`orange-heart`.`TransactionCategory`.`id`,
	`orange-heart`.`TransactionCategory`.`category`,
	`orange-heart`.`TransactionCategory`.`outflow`, 
	`orange-heart`.`TransactionCategory`.`inflow`,
	`orange-heart`.`TransactionCategory`.`memo`, 
	`orange-heart`.`TransactionCategory`.`user`, 
	`orange-heart`.`TransactionCategory`.`transactionId`, 
	`orange-heart`.`TransactionCategory`.`createdAt`
FROM `orange-heart`.`TransactionCategory`
WHERE (
	`orange-heart`.`TransactionCategory`.`user` = ? AND
	`orange-heart`.`TransactionCategory`.`category` IS NULL
)

This query is adding TransactionCategory.category IS NULL to the where clause, when it should be joining TransactionCategory.category = CategoryGroup.category and adding a WHERE clause on the category group.

The same issue is occurring the count when trying to filter on the same relational null value, and occurs whether you use categoryGroup: null or categoryGroup: { is: null } in the where clause.

If you set const group: string | undefined = "some group value";, the query is instead:

SELECT
	`orange-heart`.`TransactionCategory`.`id`,
	`orange-heart`.`TransactionCategory`.`category`,
	`orange-heart`.`TransactionCategory`.`outflow`,
	`orange-heart`.`TransactionCategory`.`inflow`,
	`orange-heart`.`TransactionCategory`.`memo`,
	`orange-heart`.`TransactionCategory`.`user`,
	`orange-heart`.`TransactionCategory`.`transactionId`,
	`orange-heart`.`TransactionCategory`.`createdAt`
FROM `orange-heart`.`TransactionCategory`
WHERE (
	`orange-heart`.`TransactionCategory`.`user` = ? AND 
	(`orange-heart`.`TransactionCategory`.`id`) IN (
        SELECT `t0`.`id` FROM `orange-heart`.`TransactionCategory` AS `t0` 
        INNER JOIN `orange-heart`.`CategoryGroup` AS `j0`
        ON (`j0`.`category`) = (`t0`.`category`)
        WHERE (`j0`.`group` = ? AND `t0`.`id` IS NOT NULL)
	)
)

Which looks more proper, and does return the appropriate results.

How to reproduce

  1. Define a model with an optional relation
model TransactionCategory {
  id            String        @id @default(uuid())
  category      String
  categoryGroup CategoryGroup? @relation(fields: [category], references: [category])
}

model CategoryGroup {
  id            String        @id @default(uuid())
  category      String
  group      String
  transactionCategories TransactionCategory[]
}
  1. Populate db with data
  2. Run a transactionCategory.findMany query with prisma using where: { categoryGroup: null }
  3. The results will be empty, even if there rows in the TransactionCategory table that have no related CategoryGroup row.

Expected behavior

When a where clause defines someRelation: null or someRelation: { is: null } on a model that has an optional relation, the resulting query should return results where someRelation = null in the underlying data.

Prisma information

Schema:

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["referentialIntegrity"]
}

datasource db {
  provider             = "mysql"
  url                  = env("DATABASE_URL")
  referentialIntegrity = "prisma"
}

model Account {
  id           String        @id @default(uuid())
  name         String
  user         String
  createdAt    DateTime      @default(now())
  transactions Transaction[]

  @@unique([user, id])
  @@unique([user, name])
}

model Transaction {
  id        String   @id @default(uuid())
  user      String
  payee     String
  date      DateTime
  createdAt DateTime @default(now())

  accountId             String
  account               Account               @relation(fields: [accountId], references: [id],  onDelete: Cascade)
  transactionCategories TransactionCategory[]
  flags                 Flag[]
  @@unique([user, id])
  @@unique([user, id, accountId])
}

model Flag {
  id           String        @id @default(uuid())
  user         String
  createdAt    DateTime      @default(now())
  name         String
  color        String //Hex Code
  transactions Transaction[]

  @@unique([user, id])
  @@unique([user, name])
}

model TransactionCategory {
  id            String        @id @default(uuid())
  category      String
  outflow       Int
  inflow        Int
  memo          String
  user          String
  transactionId String
  categoryGroup CategoryGroup? @relation(fields: [category], references: [category])
  transaction   Transaction   @relation(fields: [transactionId], references: [id],  onDelete: Cascade)
  createdAt     DateTime      @default(now())

  @@unique([id, user])
  @@unique([category, transactionId])
}

model CategoryGroup {
  id        String   @id @default(uuid())
  category  String
  group     String
  user      String
  createdAt DateTime @default(now())
  transactionCategories TransactionCategory[]

  @@unique([id, user])
  @@unique([category, user])
}

model User {
  id    String  @id
  name  String?
  email String?
}

Query in code:

db.transactionCategory.findMany({
  where: {
    user: this.user,
    categoryGroup: group ? { group } : { is: null },
  },
  include: {
    categoryGroup: true,
    transaction: {
      include: {
        flags: true,
        account: true,
      },
    },
  },
}),

Debug info on generated query:

prisma:client prisma.transactionCategory.findMany({
  prisma:client   where: {
  prisma:client     user: '<snip>',
  prisma:client     categoryGroup: {
  prisma:client       is: null
  prisma:client     }
  prisma:client   },
  prisma:client   include: {
  prisma:client     categoryGroup: true,
  prisma:client     transaction: {
  prisma:client       include: {
  prisma:client         flags: true,
  prisma:client         account: true
  prisma:client       }
  prisma:client     }
  prisma:client   }
  prisma:client }) +0ms

Generated Query:

prisma:query SELECT `orange-heart`.`TransactionCategory`.`id`, `orange-heart`.`TransactionCategory`.`category`, `orange-heart`.`TransactionCategory`.`outflow`, `orange-heart`.`TransactionCategory`.`inflow`, `orange-heart`.`TransactionCategory`.`memo`, `orange-heart`.`TransactionCategory`.`user`, `orange-heart`.`TransactionCategory`.`transactionId`, `orange-heart`.`TransactionCategory`.`createdAt` FROM `orange-heart`.`TransactionCategory` WHERE (`orange-heart`.`TransactionCategory`.`user` = ? AND `orange-heart`.`TransactionCategory`.`category` IS NULL)

Environment & setup

  • OS: MacOS
  • Database: MySQL
  • Node.js version: v14.19.2, tried with v16.15.0 as well with same result

Prisma Version

3.14.0

alexghenderson avatar May 12 '22 05:05 alexghenderson

Ok, this was a bit confusing, but I think I know what's going on.

If the group variable is set, we use the { group } syntax that is a short-hand for { group: group }. This is correct and checks the string value of the group field in the CategoryGroup model.

If the group variable is not set, we just see if the relation is not set, and is actually checking if the relation is NOT set. This is also correct.

What you'd want is a query that does something like { group: null }, and this one would generate a query you might be looking for. Of course then the group should be an optional field.

pimeys avatar Sep 02 '22 15:09 pimeys

Hey @alexghenderson, to make this a bit more explicit, here is my try to explain what Julius discovered:

It seems that your code code means actually something different than what you expect to happen in SQL:

categoryGroup: group ? { group } : null
  1. If group has a value "foo", this "expands" to: categoryGroup: { group: "foo" }. It should then query for CategoryGroup with group = foo via SQL - which it does per your description.
  2. But if group has no value, this becomes categoryGroup: null instead. That is turned into the SQL query TransactionCategory.category IS NULL - which also looks correct!

If you instead change your code to look like this:

categoryGroup: group ? { group } : { group: null }

You should get different SQL. But probably you would first get a error in Prisma Client, as CategoryGroup.group in your schema is not actually allowed to contain NULL! Change that, migrate, and it could work though.

Does that make sense to you?

janpio avatar Sep 02 '22 18:09 janpio

@alexghenderson Are you following that explanation and agree with out conclusion?

I am closing this issue now, but feel free to comment if something is still unclear or you disagree.

janpio avatar Sep 13 '22 23:09 janpio