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.

connectOrCreate deletes old relation and creates a new one

See original GitHub issue

Bug description

When there are prisma models that have an optional one-to-one relation and you are updating one of those models the connectOrCreate has unexpected behavior.

const item = await prisma.item.create({
    data: {name: 'Item 1'},
  })
  const myModel = await prisma.myModel.create({
    data: {
      name: 'MyModel 1',
      item: {connect: {id: item.id}}
    }
  })

  await prisma.item.update({
    where: {
      id: item.id
    },
    data: {
      name: 'Updated Item 1',
      myModel: {
        connectOrCreate: {
          where: {
            itemId: item.id
          },
          create: {
            name: 'MyModel 2'
          }
        }
      }
    }
  })

The result of the above code is two MyModels in the DB and the original ‘MyModel 1’ has been disconnected from its item and replaced with ‘MyModel 2’.

In our real world example at the time of executing this query we don’t currently know if the Item is connected to an existing MyModel and we are trying to avoid calling the DB to check if there is a MyModel already connected to manually perform the function that connectOrCreate should perform.

Thanks in advance for the help!!

How to reproduce

  1. Clone this example repository.
  2. Setup your DB, generate client, and run migrations.
  3. Run node index.js

Observe the output where you can see the following:

MyModel 1 has been correctly linked to item with id e4767238-0a96-4b3b-83c8-56af27c7e741
All MyModels after connectOrCreate [
  {
    id: '4e29d553-c8c9-49d6-9949-f5c683374f3f',
    name: 'MyModel 1',
    itemId: null
  },
  {
    id: '2dc291ac-8875-4dfb-99cc-e86799039384',
    name: 'MyModel 2',
    itemId: 'e4767238-0a96-4b3b-83c8-56af27c7e741'
  }
]
There should only be one MyModel in the DB!!!

Expected behavior

When connectOrCreate-ing and the model is found via a where statement that uses the linking id column, then maintain that connection instead of creating a new model.

Prisma information

datasource db {
  provider = "postgresql"
  url      = "postgresql://testuser:testpw@localhost:5432/testdb?schema=public"
}

generator client {
  provider      = "prisma-client-js"
  binaryTargets = ["native", "rhel-openssl-1.0.x"]
}


model MyModel {
  id                         String              @id @default(uuid())
  name                       String
  itemId String?             @unique
  item   Item?               @relation(references: [id], fields: [itemId])

}

model Item {
  id           String              @id @default(uuid())
  name         String
  myModel      MyModel?
}

Environment & setup

  • OS: Mac OS
  • Database: PostgreSQL
  • Node.js version: v16.13.2

Prisma Version

prisma                  : 3.9.1
@prisma/client          : 3.9.1
Current platform        : darwin-arm64
Query Engine (Node-API) : libquery-engine bcc2ff906db47790ee902e7bbc76d7ffb1893009 (at node_modules/@prisma/engines/libquery_engine-darwin-arm64.dylib.node)
Migration Engine        : migration-engine-cli bcc2ff906db47790ee902e7bbc76d7ffb1893009 (at node_modules/@prisma/engines/migration-engine-darwin-arm64)
Introspection Engine    : introspection-core bcc2ff906db47790ee902e7bbc76d7ffb1893009 (at node_modules/@prisma/engines/introspection-engine-darwin-arm64)
Format Binary           : prisma-fmt bcc2ff906db47790ee902e7bbc76d7ffb1893009 (at node_modules/@prisma/engines/prisma-fmt-darwin-arm64)
Default Engines Hash    : bcc2ff906db47790ee902e7bbc76d7ffb1893009
Studio                  : 0.457.0

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:1
  • Comments:8 (7 by maintainers)

github_iconTop GitHub Comments

1reaction
Jackman3005commented, Feb 24, 2022

@janpio I don’t think this is new behavior. We recently upgraded to 3.9.2 and had it in our old version as well (3.2.1).

0reactions
sreutercommented, May 5, 2022

Amazing work, thank you @dpetrick! 🙏

Read more comments on GitHub >

github_iconTop Results From Across the Web

Relation queries (Concepts) - Prisma
Provide transactional guarantees for creating, updating or deleting data across multiple tables in a single Prisma Client query. If any part of the...
Read more >
Create or update one to many relationship in Prisma
I'm providing my solution based on the clarifications you provided in the comments. First I would make the following changes to your Schema....
Read more >
Update - Neo4j GraphQL Library
Single update; Nested create; connectOrCreate relationships. Using the following type definitions for these examples: Graphql. Copy to Clipboard.
Read more >
CREATE TABLE - Amazon Redshift
Creates a new table in the current database. The owner of this table is the issuer of the CREATE TABLE command.
Read more >
It's Prisma Time - Update - DEV Community ‍ ‍
[entity].update , not so different from the insert and the delete, ... connect or connectOrCreate operation to create a relation between two ...
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