prisma: Improve error when updating a non-existent nested record

Node.js version: v12.13.0 Prisma2 version: prisma2@2.0.0-preview017.2

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.\")")

About this issue

  • Original URL
  • State: open
  • Created 5 years ago
  • Reactions: 2
  • Comments: 15 (11 by maintainers)

Most upvoted comments

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.

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

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

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.