prisma: "every" relation filter not working as expected

Bug description

Problem 0: “every” relation filter return all the admins that has no permissions at all. (in the n-to-n table exists no records relating this admins with some permission) This admins should not be returned because they has no permissions and the every condition is not completed.

Problem 1 (Query 1): This query return all the admins that have no permissions + all the admins that have permission 1, or 2, or 3, or 1+2+3. This is copletely wrong. It should return only the admins having 1+2+3.

Problem 2 (Query 2): This query is working partially correct returning not the 1,2,3 admins because they don’t complete the every condition but still return all the admins that have no related permissions which is obviously wrong.

How to reproduce

Follow the primsa information below.

Expected behavior

“Every” should return only the admins that complete the condition agains every relation and should ignore the admins that haven’t relations.

“Every + in” should return only admins compliting the all “every” conditions but it works like some and also return all the admins having not related permissions.

Prisma information

Schema

model Admin{
    @@map("admins")

    id      Int      @id @default(autoincrement())
    email   String   @unique
    name    String?
    permissions Permission[]
}

model Permission{
    @@map("permissions")

    id      Int      @id @default(autoincrement())
    slug String
    name String
    category String
    admins Admin[]
}

Query 1

prisma.admin.findMany({
            select: {
                id: true,
                name: true,
                email: true,
                roles: {
                    select: {name: true},
                },
                permissions: {
                    select: {name: true},
                },
            },
            where: {
                permissions: {
                    every: {
                        id: {
                            in: [1, 2, 3]
                        }
                    }
                }
            }
        })

Query 2

prisma.admin.findMany({
            select: {
                id: true,
                name: true,
                email: true,
                roles: {
                    select: {name: true},
                },
                permissions: {
                    select: {name: true},
                },
            },
            where: {
                permissions: {
                    every: {
                        id: {
                            gt: 2
                        }
                    }
                }
            }
        })

DB

#admins
1	admin@test.com admin
2	admin1@test.com admin1
3	admin2@test.com admin2
4	admin3@test.com admin3
5	admin4@test.com admin4
6	admin5@test.com admin5

#permissions 
1	test-1	test 1	test_1
2	test-2	test 2	test_2
3	test-3	test 3	test_3

#_AdminsToPermissions
1	1
1	2
1	3
2	2
3	3
3	1

Environment & setup

  • OS: Ubuntu
  • Database: PostgresSQL
  • Node.js version: v16.14.0

Prisma Version

@prisma/client": "^3.7.0
prisma": "^3.7.0

About this issue

  • Original URL
  • State: open
  • Created 5 years ago
  • Reactions: 14
  • Comments: 34 (10 by maintainers)

Most upvoted comments

@janpio

would be to add or do not ahve this relation set (= database NULL) or something similar to the explanation, did I understand that correctly?

Yes, because I would assume that the majority of people wouldn’t anticipate that every would return records with no relations. I for sure didn’t

Hi, please do like this:

prisma.admin.findMany({
            select: {
                id: true,
                name: true,
                email: true,
                roles: {
                    select: {name: true},
                },
                permissions: {
                    select: {name: true},
                },
            },
            where: {
                permissions: {
                    some: {},
                    every: {
                        id: {
                            in: [1, 2, 3]
                        }
                    }
                }
            }
        })

Add one more some just before every.

Hey, any progress on this? Started migrating my project to prisma and just ran into this

I don’t think it’s a bug, it is an expected behavior. Think of it as of following JS equivalent:

@SevInf If this is the expected behavior, then the docs are kinda misleading:

every

Returns all records where all (“every”) related records match filtering criteria.

It says: returns all records where match, but it also returns records that don’t have this relation, so they do not match the criteria

And imho every: [1,2] should only return records that have both 1+2 relations

And again if this is the expected behavior then why is this issue still open?

The question is exactly about “in” + “every” (read my first comment) and that it doesn’t work the way people expect and may cause unexpected bugs. At the end I don’t use prisma anymore because I like to have control and to work logical. If you think that it is logically correct the “in” + “every” to return also records having no relations at all and should work in this way then it’s not a bug and you should close the issue. I have nothing more to say.

In support of the existing API behaviour: it’s mathematically correct because any statement about the members of an empty set is true https://en.wikipedia.org/wiki/Empty_set

Every: “There are no items in this set for which this statement is false” Some: “There is at least one item in this set for which this statement is true” This is why combining every and some results in the desired behaviour, which is “There is at least one item in this set AND there are no items in this set for which this statement is false”

Prisma’s query language is an abstraction over SQL/noSQL so shouldn’t conform to their query language conventions. It’s an ORM for JS so absolutely should align more closely with native JS APIs. For what it’s worth Mongo does exhibit this behaviour too: https://www.mongodb.com/docs/manual/reference/operator/aggregation/allElementsTrue/

Some clarity in the docs here would be great though

@janpio Give me an example using SQL language and “in” operator that will return users that have either no permissions, permission 1, permission 2 or permissions 1+2. At the end Prisma is an layer between JS and SQL or noSQL right? The expected behavior should be like SQL or noSQL and not like JS .every function.

In support of the existing API behaviour: it’s mathematically correct because any statement about the members of an empty set is true https://en.wikipedia.org/wiki/Empty_set

Every: “There are no items in this set for which this statement is false” Some: “There is at least one item in this set for which this statement is true” This is why combining every and some results in the desired behaviour, which is “There is at least one item in this set AND there are no items in this set for which this statement is false”

Prisma’s query language is an abstraction over SQL/noSQL so shouldn’t conform to their query language conventions. It’s an ORM for JS so absolutely should align more closely with native JS APIs. For what it’s worth Mongo does exhibit this behaviour too: https://www.mongodb.com/docs/manual/reference/operator/aggregation/allElementsTrue/

Some clarity in the docs here would be great though

In my opinion, you can have a “mathematically correct” API all you want, but if people need to read the documentation 4 times and still dont get how it works, then basically the interface needs a review.

At the same time you are indeed mixing SQL (AND, OR, IN, etc) parameters and then every/some from JS so the API is not consistent, so I don’t think that is enough reason to keep it.

We are doing RAW queries every time Prisma forces us to use every/some because the behaviour is not easy to digest.

agreee with @Tronikelis 。 Are there any plans to fix this problem? Or you don’t think it’s a problem at all。

Hey, any progress on this? Started migrating my project to prisma and just ran into this

I don’t think it’s a bug, it is an expected behavior. Think of it as of following JS equivalent:

@SevInf If this is the expected behavior, then the docs are kinda misleading:

every

Returns all records where all (“every”) related records match filtering criteria.

It says: returns all records where match, but it also returns records that don’t have this relation, so they do not match the criteria

And imho every: [1,2] should only return records that have both 1+2 relations

And again if this is the expected behavior then why is this issue still open?

@apecollector every means that condition individually applies to every item in a relationship. What you query does is basically, “Give me all posts, where every tag is both { name: 'Development', color: 'Blue' } and { name: 'Programming', color: 'Pink' }”. Since conditions are mutually exclusive, you won’t get anything as a response. What you want is: give me all posts, where one of the tags is { name: 'Development', color: 'Blue' } and some other tag is { name: 'Programming', color: 'Pink' }. Which could be done with a following query:

const posts = await prisma.post.findMany({
    where: {
      AND: [
          { tags: { some: { name: 'Development', color: 'Blue' } }},
          { tags: { some: { name: 'Programming', color: 'Pink' } }},
      ]
    },
  });

@janpio those few days are actually 43. You don’t need confirmation from @adventurini to reproduce this bug, just take a look at my example. It’s clear enought.

Thank you @victorteokw for your workaround; adding some: {} yielded the expected behaviour for me, after too much time debugging what seemed like something obvious; assuming I was doing something incorrect.

My suggestion is to revisit assumptions here with the principle of least surprise in mind, but documenting what it does today feels like a minimum expectation for all users.

Thanks for Prisma though!

I don’t think it’s a bug, it is an expected behavior. Think of it as of following JS equivalent:

admins.filter(admin => { 
  return admin.permissions.every(permission => [1, 2, 3].includes(permission.id)) 
})
  1. every on an empty list is always true. This is consistent with JS, as well with SQL.
  2. Right way to read every: { id: { in: [1, 2, 3]}} is “return the admins, where every permission id is either 1, 2, 3” which is exactly what happens.

If you need to get records that have 1+2+3, you can use some combined with AND e.g. AND: permissionIds.map(id => ({ permissions: { some: { permission: { id, }, }, }

Hey all, I think I have a similar issue but have come up with a solution by changing my query. If I take the original issue at the top:

prisma.admin.findMany({
  select: {
    id: true,
    name: true,
    email: true,
    roles: {
      select: { name: true },
    },
    permissions: {
      select: { name: true },
    },
  },
  where: {
    permissions: {
      every: {
        id: {
          in: [1, 2, 3]
        },
      },
    },
  },
});

I get that ‘every’ is where you are saying every parent record matches the child condition (but with ‘in’ you are basically saying ‘OR’ so it becomes much more permissive). What you want is ‘AND’ - but this doesn’t seem to have native syntax in Prisma queries, unless you flip it and do it from the root:

prisma.admin.findMany({
  select: {
    id: true,
    name: true,
    email: true,
    roles: {
      select: { name: true },
    },
    permissions: {
      select: { name: true },
    },
  },
  where: {
    AND: [1,2,3].map((id) => ({
      permissions: {
        some: {
          id: {
            equals: id
          }
        }
      }
    }))
  },
});

I actually ended up here because of @younes-alouani examples on Tags - which is much more similar to my use case. I may have misread this issue, but I believe this will achieve what was required!

@jdkdev that JS code is exactly how this query would behave (I think you meant to have .includes(permission) in this case, not .includes(permission.id)) with exactly the same behavior described here. You can check this by using following list of admins:

const admins = [
  {
    permissions: [1, 2, 3],
  },
  {
    permissions: [1, 2],
  },

  {
    permissions: [],
  },
  {
    permissions: [4],
  },
];

in this case, all but the last admin will be returned.

I tried to achieve what you want without using raw queries and the best I could come up with 4.3.1 version is:

await prisma.admin.findMany({
    where: {
      AND: [
        { permissions: { some: { id: 1 } } },
        { permissions: { some: { id: 2 } } },
        { permissions: { some: { id: 3 } } },
        { permissions: { none: { id: { notIn: [1, 2, 3] } } } },
      ],
    },
  })

This is definitely suboptimal and are where we could’ve done better. If you’d like to stick with raw queries until we can provide something better, here is a better raw query (assuming postgres):

SELECT * FROM admins 
WHERE adminId IN (
  SELECT adminId FROM admins_permissions
  GROUP BY adminId,
  HAVING array_agg(permissionId) @> array[1, 2, 3]
)

@jdkdev will something like work for you?

prisma.admin.findMany({
            where: {
                permissions: {
                    none: {
                        id: {
                            notIn: [1, 2, 3]
                        }
                    }
                }
            }
        })

@lachezargrigorov You are assuming a lot about me and my job here. If I ask someone else to reproduce an issue, that is usually because that is the fastest way to move an issue forward.

Thanks @adventurini.