Skip to content

Improve error when updating a non-existent nested record #5015

Open

Description

@vadim-shilov

Node.js version: v12.13.0
Prisma2 version: [email protected]

Schema:

generator photon {
  provider = "photonjs"
}

datasource db {
  provider = "sqlite"
  url      = "file:{**PATH**}/db.sqlite"
}

model ParentRec { @@map(name: "parent")
  id        String   @default(cuid()) @id
  createdAt DateTime @default(now()) @map(name: "created_at")
  updatedAt DateTime @updatedAt @map(name: "updated_at")
  code      String   @unique
  children  ChildRec[]
}

model ChildRec { @@map(name: "child")
  id        String    @default(cuid()) @id
  createdAt DateTime  @default(now()) @map(name: "created_at")
  updatedAt DateTime  @updatedAt @map(name: "updated_at")
  code      String    @unique
  parent    ParentRec @map(name: "parent_id")
}

Code:

const {Photon} = require('@prisma/photon');

async function main() {
    const photon = new Photon();
    await photon.connect();
    try {
        const created = await photon.parentRecs.create({
            data: {
                code: 'parent',
                children: {
                    create: {
                        code: 'child'
                    }
                }
            },
            include: {
                children: true
            }
        });

        console.log(created);

        const updated = await photon.parentRecs.update({
            where: {
                code: 'parent'
            },
            data: {
                children: {
                    update: {
                        where: {
                            code: 'not_found' // rec with this code doesn't exist
                        },
                        data: {
                            code: 'child_upd'
                        }
                    }
                }
            },
            include: {
                children: true
            }
        });

        console.log(updated);
    } catch (err) {
        console.error(err);
    } finally {
        await photon.disconnect();
    }
}

main().then(() => {
    console.log('Completed!');
});

Error:

Error: 
Invalid `photon.()` invocation in /home/vadim/Projects/Temp/index.js:23:49

Reason: Error occurred during query execution:
InterpretationError("Error for binding \'1\': AssertionError(\"Expected a valid parent ID to be present for nested update to-one case.\")")

Activity

  1. pantharshit00 commented on Dec 5, 2019

    @pantharshit00
    Contributor

    This is expected as the relationship is required. Trying to perform an update on a non-existant record will throw. We need to throw a better here though.

  2. janpio commented on Dec 5, 2019

    @janpio
    Contributor

    (Possible that the error is already better in alpha - please check that @pantharshit00)

  3. pantharshit00 commented on Dec 6, 2019

    @pantharshit00
    Contributor

    Nope, it is throwing the same error in alpha.415
    image

  4. dpetrick commented on Dec 19, 2019

    @dpetrick
    Contributor

    Throwing the error here is correct. The message is not useful, which is known but unrelated to this issue.

  5. assigned and unassigned on Jan 16, 2020
  6. tomhoule commented on Jan 30, 2020

    @tomhoule
    Contributor

    Status update: there are big changes ongoing in the query engine. I haven't worked on this.

  7. tomhoule commented on Feb 11, 2020

    @tomhoule
    Contributor

    The query engine refactoring has started landing, so I checked whether this crash is still reproducible, and it is. Working on this now.

  8. tomhoule commented on Feb 11, 2020

    @tomhoule
    Contributor

    This PR contains a test reproduction using the same schema and queries as above. @mavilein as mentioned on slack, this looks very AUMFIDARR-relevant. The TL;DR is that a parent ID is missing on a nested update, where the parent record is found by unique criteria, and the child record too (they also have PKs but they are not used there)

  9. changed the title [-]Photon returns an error on update a nested rec[/-] [+]Prisma Client returns an error on update a nested rec[/+] on Feb 13, 2020
  10. 11 remaining items

  11. added this to the 2.18.0 milestone on Feb 17, 2021
  12. matthewmueller commented on Feb 24, 2021

    @matthewmueller
    Contributor

    Just double-checked this, still running into an unhelpful error. I feel like the confusing part is the "valid parent ID", it's a valid ID, it's just that this ID doesn't exist.

    PrismaClientKnownRequestError2 [PrismaClientKnownRequestError]: 
    Invalid `prisma.user.update()` invocation:
    
      Query interpretation error. Error for binding '1': AssertionError("Expected a valid parent ID to be present for nested update to-one case.")
        at cb (/Users/m/dev/src/github.com/prisma/qa-errors/node_modules/@prisma/client/runtime/index.js:78689:17)
        at processTicksAndRejections (internal/process/task_queues.js:97:5) {
      code: 'P2016',
      clientVersion: '2.17.0',
      meta: {
        details: `Error for binding '1': AssertionError("Expected a valid parent ID to be present for nested update to-one case.")`
      }
    }
    
    // This is your Prisma schema file,
    // learn more about it in the docs: https://pris.ly/d/prisma-schema
    
    datasource db {
      provider = "postgresql"
      url      = env("DATABASE_URL")
    }
    
    generator client {
      provider = "prisma-client-js"
    }
    
    model User {
      id    Int    @id
      name  String
      posts Post[]
    }
    
    model Post {
      id     Int    @id
      title  String
      user   User   @relation(fields: [userId], references: [id])
      userId Int
    }
    
    import { PrismaClient } from '@prisma/client'
    
    const client = new PrismaClient()
    
    async function main() {
      await client.$connect()
      await client.user.create({
        data: {
          id: 1,
          name: "Alice",
          posts: {
            create: [
              {
                id: 1,
                title: "A"
              },
              {
                id: 2,
                title: "B"
              }
            ]
          }
        }
      })
      await client.user.update({
        where: {
          id: 1,
        },
        data: {
          posts: {
            update: {
              where: {
                id: 3
              },
              data: {
                title: "C"
              }
            }
          }
        }
      })
    }
    
    main().catch(console.error).finally(() => client.$disconnect())
    prisma               : 2.17.0
    @prisma/client       : 2.17.0
    Current platform     : darwin
    Query Engine         : query-engine 3c463ebd78b1d21d8fdacdd27899e280cf686223 (at node_modules/@prisma/engines/query-engine-darwin)
    Migration Engine     : migration-engine-cli 3c463ebd78b1d21d8fdacdd27899e280cf686223 (at node_modules/@prisma/engines/migration-engine-darwin)
    Introspection Engine : introspection-core 3c463ebd78b1d21d8fdacdd27899e280cf686223 (at node_modules/@prisma/engines/introspection-engine-darwin)
    Format Binary        : prisma-fmt 3c463ebd78b1d21d8fdacdd27899e280cf686223 (at node_modules/@prisma/engines/prisma-fmt-darwin)
    Studio               : 0.353.0
    
  13. changed the title [-]Prisma Client returns an error on update a nested rec[/-] [+]Improve error when updating a non-existent nested record[/+] on Feb 24, 2021
  14. matthewmueller commented on Mar 1, 2021

    @matthewmueller
    Contributor

    We did a pass over the errors and this one isn't easy to improve. We'll get to it eventually, but not right now.

  15. removed their assignment
    on Mar 1, 2021
  16. haggalin commented on Mar 25, 2022

    @haggalin

    Tested this with:

    @prisma/client          : 3.10.0
    Current platform        : debian-openssl-1.1.x
    Query Engine (Node-API) : libquery-engine 73e60b76d394f8d37d8ebd1f8918c79029f0db86 (at node_modules/@prisma/engines/libquery_engine-debian-openssl-1.1.x.so.node)
    Migration Engine        : migration-engine-cli 73e60b76d394f8d37d8ebd1f8918c79029f0db86 (at node_modules/@prisma/engines/migration-engine-debian-openssl-1.1.x)
    Introspection Engine    : introspection-core 73e60b76d394f8d37d8ebd1f8918c79029f0db86 (at node_modules/@prisma/engines/introspection-engine-debian-openssl-1.1.x)
    Format Binary           : prisma-fmt 73e60b76d394f8d37d8ebd1f8918c79029f0db86 (at node_modules/@prisma/engines/prisma-fmt-debian-openssl-1.1.x)
    Default Engines Hash    : 73e60b76d394f8d37d8ebd1f8918c79029f0db86
    Studio                  : 0.458.0

    Tested some different cases here:

    Normal update

    await prisma.user.update({
        where: {
            uuid: 'non-existing-id'
        },
        data: {
            username: 'newUsername'
        }
    });
    

    Throws P2025 with meta.cause: 'Record to update not found.'

    Update with a nested create

    await prisma.user.update({
        where: {
            uuid: 'non-existing-id'
        },
        data: {
            username: 'newUsername',
            contact: {
               create: {
                  phoneNumber: '123456'
               }
            }
        }
    });
    

    Throws P2025 with meta.cause: "No 'User' record (needed to inline the relation with create on 'Contact' record) was found for a nested create on one-to-one relation 'ContactToUser'."

    Update with a nested update

    await prisma.user.update({
        where: {
            uuid: 'non-existing-id'
        },
        data: {
            username: 'newUsername',
            contact: {
               update: {
                  phoneNumber: '123456'
               }
            }
        }
    });
    

    Throws P2016 with meta.details: "Error for binding '1': AssertionError("Expected a valid parent ID to be present for nested update to-one case.")"

    I guess the expectation here is that in the nested update case the error code should be P2025 and a the error message something similar to the message in the nested create case.

  17. zomars commented on Apr 1, 2022

    @zomars

    Thanks to your comment I was able to debug this @haggalin 🙏🏽

  18. reisblucas commented on Jul 23, 2022

    @reisblucas

    Same error, but in my case, was unknown the cause, initially I thinked was my field as decimal 0.00. Tested manually with query in MySQL and executed the query again with the field assigned with the value 1 and the same error occurs.

    private updateAccount = (
        quantity: number,
        uidToken: number,
        op: string,
        operationType: number,
      ) => this.prisma.users
        .update({
          data: {
            AccountsBalance: {
              update: {
                data: {
                  balance: {
                    [op]: quantity,
                  },
                },
                where: {
                  id: uidToken,
                },
              },
            },
            AccountsStatement: {
              create: {
                value: quantity,
                OperationTypes_id: operationType,
                created_at: changeFormat(newDateMethods
                  .removeTZ(new Date()), 'ymd'),
              },
            },
          },
          where: {
            id: uidToken,
          },
        });
    

    My last option, was try reseting my db and seeding again and solved with the same query used before.

    I don't know what is the problem and can't see another form beyond that, hope it helps someone.

  19. reisblucas commented on Jul 23, 2022

    @reisblucas

    Appending to my comment above, this was the transaction.

    ...
    try {
          await this.prisma.$transaction(
            [this.updateAccount(quantity, uidToken, 'increment', OperationId.DEPOSIT)],
          );
        } catch (e) {
          if (e instanceof PrismaClientUnknownRequestError) {
            console.log('Error in accounts service:', e.message);
            throw new HttpException(StatusCodes.BAD_REQUEST, e.message);
          }
        }
    ...
    
  20. gautamsi commented on Sep 29, 2024

    @gautamsi

    came across this, IMO we should be able to specify if error should be thrown on non existent entity. For example I would like the item marked archived if the parent item is archiving and the nested item exist, if it does not exist there should not be any problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions