question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Relation filter operator 'every' does not work correctly

See original GitHub issue

Bug description

Relation filter.

Relation filter operator ‘every’ does not work correctly. ‘Every’ will return records in case there’s no related record (relation field of that record is an empty array) regardless of filter conditions

How to reproduce

Schema

Similar to this Client API Reference

model ExtendedProfile {
  id        Int    @id @default(autoincrement())
  biography String
  user      User   @relation(fields: userId, references: id)
  userId    Int
}
model User {
  id           Int             @id @default(autoincrement())
  name         String?
  email        String          @unique
  profileViews Int             @default(0)
  role         Role            @default(USER)
  coinflips    Boolean[]
  posts        Post[]
  profile      ExtendedProfile?
}
model Post {
  id         Int        @id @default(autoincrement())
  title      String
  published  Boolean    @default(true)
  author     User       @relation(fields: [authorId], references: [id])
  authorId   Int
  comments   Json?
  views      Int        @default(0)
  likes      Int        @default(0)
  categories Category[]
}
model Category {
  id    Int    @id @default(autoincrement())
  name  String @unique
  posts Post[]
}
enum Role {
  USER
  ADMIN
}

Query

const result = await prisma.user.findMany({
    where: {
      posts: {
        // add 'some' here will explicitly fix
        // some: {},
        every: {
          views: {
            gt: 10,
          },
        },
      },
    },
  });

Result

Assuming that user id 11 has no post image the result still includes it

Environment & setup

  • OS: , Windows
  • Database: PostgreSQL,
  • Node.js version: 14.5.5
  • Prisma version:
Environment variables loaded from .env
prisma               : 2.20.1
@prisma/client       : 2.20.1
Current platform     : windows
Query Engine         : query-engine 60ba6551f29b17d7d6ce479e5733c70d9c00860e (at node_modules\@prisma\engines\query-engine-windows.exe)
Migration Engine     : migration-engine-cli 60ba6551f29b17d7d6ce479e5733c70d9c00860e (at node_modules\@prisma\engines\migration-engine-windows.exe)
Introspection Engine : introspection-core 60ba6551f29b17d7d6ce479e5733c70d9c00860e (at node_modules\@prisma\engines\introspection-engine-windows.exe)
Format Binary        : prisma-fmt 60ba6551f29b17d7d6ce479e5733c70d9c00860e (at node_modules\@prisma\engines\prisma-fmt-windows.exe)
Default Engines Hash : 60ba6551f29b17d7d6ce479e5733c70d9c00860e
Studio               : 0.365.0

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:5
  • Comments:7 (6 by maintainers)

github_iconTop GitHub Comments

2reactions
dpetrickcommented, Apr 22, 2021

Edit: It wasn’t clear in the initial post, but the behavior that records without relations are returned here is related directly to the odd inverted condition in the generated SQL.

I looked into the issue and discovered that the generated SQL is not really intuitive:

SELECT
    "public"."ModelA"."id"
FROM
    "public"."ModelA"
WHERE
    ("public"."ModelA"."id") NOT IN (
        SELECT
            "t0"."id"
        FROM
            "public"."ModelA" AS "t0"
            INNER JOIN "public"."ModelB" AS "j0" ON ("j0"."a_id") = ("t0"."id")
        WHERE
            (
                (NOT "j0"."counter" >= 0)
                AND "t0"."id" IS NOT NULL
            )
    )

Intuitively, the SQL should (simplified) be:

SELECT
    "t0"."id"
FROM
    "public"."ModelA" AS "t0"
    INNER JOIN "public"."ModelB" AS "j0" ON ("j0"."a_id") = ("t0"."id")
WHERE
      "j0"."counter" >= 0

Note that the current version inverts the filter condition (NOT "j0"."counter" >= 0), which is odd. I will ask around why that’s the case. Straight up changing the behavior is hard, I will schedule follow-up work on this.

1reaction
mentos1386commented, Jun 21, 2021

Is there any workaround for this issue?

EDIT: I didn’t see it in the initial post at first… Adding some: {} is a workaround 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

Service Layer API filter - operator 'or' does not work properly
Hi Experts,. We were wondering if the filter with 'or', 'eq' and primary key field does not work properly in service layer API....
Read more >
Filter Query in List Records not working for Lookup fields
Solved: Hi PowerUsers, I am trying to list/get records from CDS "Leave Request" entity on the basis of a WorkerID. WorkerId is a...
Read more >
Filtering and sorting (Concepts) - Prisma
Use the Prisma Client API to filter records by any combination of fields or related record fields, and sort the results.
Read more >
Operators available for filters and queries
The system provides a set of operators for use with filters, condition builders, and encoded queries. The data type of a field determines ......
Read more >
Express-Postgres fails to apply array filter: error: operator does ...
This should work: exports.getReplies = async function (commentID) { commentID = parseInt(commentID); console.log(commentID); return await ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found