Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

_count doesn't update in many to many relation #12557

Closed
Tracked by #11441
Sakkhor909 opened this issue Mar 28, 2022 · 8 comments
Closed
Tracked by #11441

_count doesn't update in many to many relation #12557

Sakkhor909 opened this issue Mar 28, 2022 · 8 comments
Labels
bug/2-confirmed Bug has been reproduced and confirmed. kind/bug A reported bug. team/client Issue for team Client. topic: _count https://www.prisma.io/docs/concepts/components/prisma-client/aggregation-grouping-summarizing#count- topic: database-provider/planetscale topic: relationMode formerly `referentialIntegrity`
Milestone

Comments

@Sakkhor909
Copy link

Sakkhor909 commented Mar 28, 2022

Bug description

I have many-to-many relations in my schema like brand and category. I am using _.count to see how many brands are there in a category. It seems to work but when I delete one of the brand it does not update _.count in the category.

This is the model :

model Category {
  id        String              @id @default(cuid())
  name       String              @unique
  createdAt DateTime            @default(now())
  brands Brand[]
}

model Brand {
  id         String              @id @default(cuid())
  name       String              @unique
  createdAt  DateTime            @default(now())
  categories   Category[] 
}

I am showing how many brands in a category by pulling the data like this

   const Data = await prisma.category.findMany({
        include: {
          _count: {
            select: { brands: true }
          }
        }
      });

It works fine. It shows how many brands are in a category.
When I try to delete a brand like this;

 prisma.brand
      .delete({
        where: {
          id: ID
        }
      })

The brand gets deleted but the category list doesn't update. It still includes that brand in _count.
I have deleted the same way in one-to-many relation where _count updated. How do I do it in many to many?

How to reproduce

The project is complicated so If you want you can use just two models to follow the bugs

model Category {
  id        String              @id @default(cuid())
  name       String              @unique
  createdAt DateTime            @default(now())
  brands Brand[]
}

model Brand {
  id         String              @id @default(cuid())
  name       String              @unique
  createdAt  DateTime            @default(now())
  categories   Category[] 
}

Expected behavior

When I delete a brand, the Category list (._count) also should be updated. like when I use this code to see.

   const Data = await prisma.category.findMany({
        include: {
          _count: {
            select: { brands: true }
          }
        }
      });

Environment & setup

  • OS: Windows 10
  • Database: MySQL
  • Node.js version: v16.14.1

Prisma Version

prisma                  : 3.11.0
@prisma/client          : 3.11.0
Current platform        : windows
Query Engine (Node-API) : libquery-engine b371888aaf8f51357c7457d836b86d12da91658b (at node_modules\@prisma\engines\query_engine-windows.dll.node)
Migration Engine        : migration-engine-cli b371888aaf8f51357c7457d836b86d12da91658b (at node_modules\@prisma\engines\migration-engine-windows.exe)
Introspection Engine    : introspection-core b371888aaf8f51357c7457d836b86d12da91658b (at node_modules\@prisma\engines\introspection-engine-windows.exe)
Format Binary           : prisma-fmt b371888aaf8f51357c7457d836b86d12da91658b (at node_modules\@prisma\engines\prisma-fmt-windows.exe)
Default Engines Hash    : b371888aaf8f51357c7457d836b86d12da91658b
Studio                  : 0.458.0
Preview Features        : referentialIntegrity

@Sakkhor909 Sakkhor909 added the kind/bug A reported bug. label Mar 28, 2022
@janpio janpio added topic: database-provider/planetscale topic: relationMode formerly `referentialIntegrity` bug/1-unconfirmed Bug should have enough information for reproduction, but confirmation has not happened yet. team/client Issue for team Client. topic: _count https://www.prisma.io/docs/concepts/components/prisma-client/aggregation-grouping-summarizing#count- labels Mar 28, 2022
@janpio janpio mentioned this issue Jul 1, 2022
35 tasks
@jkomyno jkomyno added bug/2-confirmed Bug has been reproduced and confirmed. and removed bug/1-unconfirmed Bug should have enough information for reproduction, but confirmation has not happened yet. labels Aug 9, 2022
@jkomyno
Copy link
Contributor

jkomyno commented Aug 9, 2022

I can confirm this bug with the current version of Prisma with referentialIntegrity = prisma.
If we use referentialIntegrity = foreignKeys, instead, everything seems to be fine.
I have target databases MySQL 8.0 and Postgres 14, but the issue doesn't seem connector-related.

Schema

    generator client {
      provider = "prisma-client-js"
      previewFeatures = ["referentialIntegrity"]
    }
    
    datasource db {
      provider = "mysql"
      url      = env("DATABASE_URI_MYSQL")
      referentialIntegrity = "prisma"
    }
    
    model Category {
      id     String  @id @default(cuid())
      name   String  @unique
      brands Brand[]
    }
    
    model Brand {
      id         String     @id @default(cuid())
      name       String     @unique
      categories Category[] 
    }

## Test

await prisma.category.create({
  data: {
    name: 'cat-1',
    brands: {
      create: [{ name: 'brand-1' }, { name: 'brand-2' }],
    },
  },
})

await prisma.category.create({
  data: {
    name: 'cat-2',
    brands: {
      create: [{ name: 'brand-3' }, { name: 'brand-4' }],
    },
  },
  include: { brands: true },
})

const categories = await prisma.category.findMany({
  include: {
    _count: {
      select: { brands: true },
    },
  },
})
expect(categories).toMatchObject([
  {
    _count: { brands: 2 },
    name: 'cat-1',
  },
  {
    _count: { brands: 2 },
    name: 'cat-2',
  }
])

await prisma.brand.delete({ where: { name: 'brand-1' } })

const categoriesAfterBrand1Deletion = await prisma.category.findMany({
  include: {
    _count: {
      select: { brands: true },
    },
  },
})
expect(categoriesAfterBrand1Deletion).toMatchObject([
  {
    _count: { brands: 1 }, // the count is 2 with referentialIntegrity = prisma
    name: 'cat-1',
  },
  {
    _count: { brands: 2 },
    name: 'cat-2',
  }
])

@pimeys
Copy link
Contributor

pimeys commented Sep 6, 2022

With 4.3.1 I cannot reproduce this issue anymore. I ran the given script and got the right result both times. Can you maybe test it again with the latest version @Sakkhor909?

@Sakkhor909
Copy link
Author

With 4.3.1 I cannot reproduce this issue anymore. I ran the given script and got the right result both times. Can you maybe test it again with the latest version @Sakkhor909?

Ok, I will update and see. Should I do anything extra ?

@pimeys
Copy link
Contributor

pimeys commented Sep 6, 2022

Read the docs:

https://www.prisma.io/docs/guides/upgrade-guides/upgrading-versions/upgrading-to-prisma-4

Most of the time db pull should be enough.

@Jolg42 Jolg42 assigned Jolg42 and unassigned pimeys and Jolg42 Sep 7, 2022
@Jolg42
Copy link
Member

Jolg42 commented Sep 7, 2022

I can reproduce with 4.2.1 but not 4.3.1, it seems it was fixed.

@jkomyno
Copy link
Contributor

jkomyno commented Sep 7, 2022

My reproduction above still stands for the following recent Prisma versions:

  • 4.1.0
  • 4.2.0
  • 4.2.1

@Jolg42 Jolg42 closed this as completed Sep 7, 2022
@Sakkhor909
Copy link
Author

Yes. The issue has solved!!!

@Jolg42 Jolg42 added this to the 4.3.0 milestone Sep 8, 2022
@Jolg42
Copy link
Member

Jolg42 commented Sep 9, 2022

After a short investigation I found out that it was fixed in our internal dev version 4.3.0-dev.37
The prisma-engines PR is about the new preview feature filteredRelationCount from @Weakky prisma/prisma-engines#3057
It seems the PR accidentally fixed this issue?

Jolg42 added a commit that referenced this issue Oct 13, 2022
…tabases (#14221)

* test(client): prototype referential integrity tests

Related: #10806

Test Suites: 1 failed, 1 total
Tests:       3 failed, 45 passed, 48 total
Snapshots:   0 total
Time:        9.838 s

* exclude mongodb to see if types tests fail like locally

* wip rewrite with Alberto

* chore: update tests

* chore: used .rejects.toThrowError

* chore: started adding ref actions

* chore: mongodb only supports 'referentialIntegrity: prisma'

* chore: added support for conditional error messages

* wip

reorg with describe
revert matrix and schema changes
beforeEach check and create users with profiles

* fix referentialIntegrityLine

* add skeleton for 1:n and m:n tests

* chore: highlighted some test errors with mongodb

* chore: added create tests for 1:n relationship

* chore: added TODO comment

* WIP m:n for SQL databases

* ci: try running github actions matrix with our tests only

* ci: remove needs: detect_jobs_to_run

* ci: fix os matrix

* ci: small CI env var tweak

* ci: fix bash line

* chore: added some update/delete tests for 1:n

* chore: added comments to _matrix.ts

* postgresql m:n all referential actions

* merge main

* DEFAULT, exclude Restrict from SQL Server, fix tests

* add mongodb tests for m:n

* chore: added some additional ref actions, added support for SQL Server

* chore: fixed bug with DEFAULT not tested, added upsert test, fixed some conditional errors, found panic on SQLServer with SetDefault

* reuse sql schema for mongodb 1:1 1:n

* 1:1 test all referral actions for onDelete & clean

* chore: improved ref actions, fixed failing tests

* chore: reproduced issue #14271

* chore: split relationships in separate files

* split m:n mongodb tests into its own file

* add `enabled Boolean?` on 1-to-n

It's a reproduction of #13766

* m:n add comments where RI=prisma - Cascade resolves instead of failing in update and create

* add `published   Boolean?` to MongoDB and update tests

* 1:1 add `enabled Boolean?` and MongoDB update tests

* add `published   Boolean?` to m:n with update tests

* chore: updated sql server tests

* add comments to m:n

[skip ci]

* add a mongodb test for immutable _id

* full database matrix for CI

* split schemas into simple files

* m to n MongoDB: change tests to match current implementation expectations

* chore: add JSON support to getTestSuiteFullName

* chore: moved ref integrity utils to its own folder. Added builder pattern to conditional error. Added matrix generation. Extracted self-contained utilities out of _schema.ts file.

* chore: added sqlite support and referentialIntegrity=prisma snapshots to 1:1 and 1:n relations

* chore: pnpm-lock

* chore: removed temp folder that wasn't supposed to be committed

* chore: imported right 'checkIfEmpty' util for m:n relation

* clean and add sqlite on m to n

* m to n add RI=Prisma messages as comments + small edits

add expectation even for `toThrowError()` cases

* m:n: split 1 test for prisma/foreignKeys

* chore: added prisma snapshots and errors as comments in m:n relation (no MongoDB yet)

* chore: added mongodb and comments to _matrix

* fix: moved _referential-integrity-utils to _utils/referential-integrity to support  ERR_PNPM_NO_SCRIPT  Missing script: test:functional-code command

* update matrix for MongoDB: add SetNull

* chore: added comments to m:n

* m to n: small edits for RI=prisma

* test 1:1 / 1:n add expects for expected throws and fix some RI=prisma messages

* chore: prettier

* 1:1 handle error messages depending on RI=prisma/foreignKeys

* * simplify conditionals

* m to n: change expectations to match current state

* chore: comment skipped test

* sqlite: skip createMany in 1:n relations

* chore: added missing sqlite snapshots to 1:n relation

* 1:n add missing delete action variants

* 1:n simplify and handle expected RI=prisma tests that should succeed

* chore: added reproduction of issue #10000

* chore: updated reproduction of issue #10000

* chore: reproduce issue #12378

* 1:1 separate onUpdate: Restrict, NoAction

* 1:1 fix create test from should throw to should succeed

* ci: separate action test for each relation / file

* ci: continue-on-error: true

* fix: referential actions test params

* fix ts checks

* only run pnpm run test:functional:code filename

* fix Cannot destructure property 'onDelete' of 'suiteConfig.referentialActions' as it is undefined.

* chore: added reproduction of issue #12557

* chore: add assertions to nested child connect in 1:1

* chore: clean unused code and better describe title

* test: add test about NO ACTION behavior with DEFERRABLE constraint

* manually bump engines

* chore: rename referentialIntegrity datasource property to relationMode

* fix github actions

* fix test about 14759 and RELATION_MODE env var

* cleanup some reproduce-x test cases

* add sqlite error snapshot

* remove continue-on-error

* remove outdated comments

* ci: remove last continue-on-error: true

* test: add `SetNull` to the matrix only for relationMode=prisma

* ci: add continue-on-error: true to run all tests

* fix snapshot with lowerace table name and run SQL Server

* exclude SQL Server / SetNull when relationMode !== prisma

* fix computeMatrix for SQL Server Restrict emulation which is not implemented

* change failing tests (issue 15683) to use .failing

* fix SQL Server test

* test(reproductions): fix empty test name

* fix relationMode = prisma SQL Server error snapshot

* fix relationMode = prisma SQL Server error snapshot

* fix relationMode = prisma SQL Server error snapshot

* comment vitess docker image (unused) and put back timeout to 60s

* test: fix snapshots for field-reference

* test: fix snapshot and getTestSuiteParametersString

* ignore expected type errors

* add note about SetNull is not run for foreignKeys in the test suite

* test: tweak comment and fix 1:1 test snapshots

* Unused '@ts-expect-error' directive.

* add `--relation-mode-tests-only` to unblock merge

* test: skip NoAction for PostgreSQL and SQLite

Related prisma/prisma-engines#3274

* fix relationMode value

* fix test name + comments

* cleanup matrix and move reproduce tests to issues directory

* add test for referentialIntegrity="prisma"

Closes #15736

* cleanup comments and misleading `toThrowError()` for expected to fail tests

* chore: removed useless comment

* chore: removed useless comments

* fix imports for moved tests in issues directory

Co-authored-by: jkomyno <skiabo97@gmail.com>
Co-authored-by: Alberto Schiabel <jkomyno@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug/2-confirmed Bug has been reproduced and confirmed. kind/bug A reported bug. team/client Issue for team Client. topic: _count https://www.prisma.io/docs/concepts/components/prisma-client/aggregation-grouping-summarizing#count- topic: database-provider/planetscale topic: relationMode formerly `referentialIntegrity`
Projects
None yet
Development

No branches or pull requests

7 participants