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

Runtime error that occurs in findUnique() when unique constraint is composed of one field #24241

Open
mmmmicha opened this issue May 20, 2024 · 1 comment
Labels
bug/2-confirmed Bug has been reproduced and confirmed. domain/client Issue in the "Client" domain: Prisma Client, Prisma Studio etc. kind/bug A reported bug. topic: typescript topic: validation

Comments

@mmmmicha
Copy link

Bug description

After configuring the schema as shown below(Prisma information), the userId set as a unique constraint was mapped to whereArgs of findUnique(). There is no type error or compile error, but the following error occurs at runtime.

PrismaClientValidationError: 
Invalid `this.readOnlyPrisma.test.findUnique()` invocation in
/Users/test/Workspace/test_monorepo/dist/apps/api/src/test/test.v3.service.js:1302:73

  1299 getTest(userId) {
  1300     var _a;
  1301     return __awaiter(this, void 0, void 0, function* () {
→ 1302         const test = yield this.readOnlyPrisma.test.findUnique({
                 where: {
                   userId: 1219,
               ?   id?: Int,
               ?   AND?: TestWhereInput | TestWhereInput[],
               ?   OR?: TestWhereInput[],
               ?   NOT?: TestWhereInput | TestWhereInput[],
               ?   createdAt?: DateTimeFilter | DateTime,
               ?   updatedAt?: DateTimeFilter | DateTime,
               ?   score?: IntFilter | Int,
               ?   user?: UserRelationFilter | UserWhereInput,
               ?   history?: TestHistoryListRelationFilter
                 },
                 select: {
                   score: true
                 }
               })

Argument `where` of type TestWhereUniqueInput needs at least one of `id` or `Test_userId_unique_constraint` arguments. Available options are marked with ?.
    at Tn (/Users/test/Workspace/test_monorepo/node_modules/@prisma/client/runtime/library.js:115:6855)
    at In.handleRequestError (/Users/test/Workspace/test_monorepo/node_modules/@prisma/client/runtime/library.js:122:6510)
    at In.handleAndLogRequestError (/Users/test/Workspace/test_monorepo/node_modules/@prisma/client/runtime/library.js:122:6188)
    at In.request (/Users/test/Workspace/test_monorepo/node_modules/@prisma/client/runtime/library.js:122:5896)
    at async l (/Users/test/Workspace/test_monorepo/node_modules/@prisma/client/runtime/library.js:127:11167)

The Test_userId_unique_constraint mentioned here does not currently exist in TestWhereUniqueInput. (Please refer to the prisma information below). As a result, a type error occurs when trying to apply Test_userId_unique_constraint to the where condition only. (As a result of my testing, id and Test_userId_unique_constraint are not set to Where condition. If you pass it together, the type error seems to be avoided. However, I don't want to use the unique condition while passing the id like this). In fact, if you use userId(defined as unique), the type error does not occur. However, as mentioned earlier, a more serious runtime error occurs.

How to reproduce

Please check prisma information part

Expected behavior

No response

Prisma information

// Add your schema.prisma
model Test {
  id        Int                   @id @default(autoincrement())
  createdAt DateTime              @default(now()) @db.Timestamptz(3)
  updatedAt DateTime              @updatedAt @db.Timestamptz(3)
  userId    Int
  user      User                  @relation(fields: [userId], references: [id])
  score     Int                   @default(0)
  history   TestHistory[]

  @@unique([userId], name: "Test_userId_unique_constraint")
  @@index([createdAt])
}
// Add your code using Prisma Client
const test = await this.readOnlyPrisma.test.findUnique({
      where: {
        userId, // <--- occured here
      },
      select: {
        score: true,
      },
    });
// index.d.ts
export type TestWhereUniqueInput = Prisma.AtLeast<
  {
    id?: number;
    userId?: number;
    AND?: TestWhereInput | TestWhereInput[];
    OR?: TestWhereInput[];
    NOT?: TestWhereInput | TestWhereInput[];
    createdAt?: DateTimeFilter<'Test'> | Date | string;
    updatedAt?: DateTimeFilter<'Test'> | Date | string;
    score?: IntFilter<'Test'> | number;
    user?: XOR<UserRelationFilter, UserWhereInput>;
    history?: TestHistoryListRelationFilter;
  },
  'id' | 'Test_userId_unique_constraint'
>;

Environment & setup

  • OS: macOS
  • Database: PostgreSQL
  • Node.js version: v20.10.0

Prisma Version

prisma                  : 5.14.0
@prisma/client          : 5.13.0
Computed binaryTarget   : darwin-arm64
Operating System        : darwin
Architecture            : arm64
Node.js                 : v20.10.0
Query Engine (Node-API) : libquery-engine e9771e62de70f79a5e1c604a2d7c8e2a0a874b48 (at node_modules/@prisma/engines/libquery_engine-darwin-arm64.dylib.node)
Schema Engine           : schema-engine-cli e9771e62de70f79a5e1c604a2d7c8e2a0a874b48 (at node_modules/@prisma/engines/schema-engine-darwin-arm64)
Schema Wasm             : @prisma/prisma-schema-wasm 5.14.0-25.e9771e62de70f79a5e1c604a2d7c8e2a0a874b48
Default Engines Hash    : e9771e62de70f79a5e1c604a2d7c8e2a0a874b48
Studio                  : 0.500.0
@mmmmicha mmmmicha added the kind/bug A reported bug. label May 20, 2024
@laplab laplab added bug/1-unconfirmed Bug should have enough information for reproduction, but confirmation has not happened yet. topic: validation domain/client Issue in the "Client" domain: Prisma Client, Prisma Studio etc. topic: typescript labels May 24, 2024
@jkomyno
Copy link
Contributor

jkomyno commented May 30, 2024

Hi, I've reproduced this issue with Prisma 5.14.0.

  • schema.prisma

    generator client {
      provider        = "prisma-client-js"
    }
    
    datasource db {
      provider = "postgres"
      url      = env("TEST_POSTGRES_URI")
    }
    
    model User {
      id   Int    @id @default(autoincrement())
      name String
      Test Test?
    }
    
    model Test {
      id        Int      @id @default(autoincrement())
      createdAt DateTime @default(now()) @db.Timestamptz(3)
      updatedAt DateTime @updatedAt @db.Timestamptz(3)
      userId    Int
      user      User     @relation(fields: [userId], references: [id])
      score     Int      @default(0)
    
      @@unique([userId], name: "Test_userId_unique_constraint")
      @@index([createdAt])
    }
    
  • TypeScript snippet

    import { PrismaClient } from '.prisma/client'
    
    async function main() {
      const prisma = new PrismaClient()
      const user = await prisma.user.create({
        data: {
          id: 1,
          name: 'jkomyno'
        }
      })
    
      console.log(user)
      
      // Add your code using Prisma Client
      const test = await prisma.test.findUnique({
        where: {
          userId: 1, // <--- occured here
        },
        select: {
          score: true,
        },
      });
    
      console.log(test)
    }
    
    void main().catch((e) => {
      console.log(e.message)
      process.exit(1)
    })
  • Output:

    { id: 1, name: 'Alberto' }
    
    Invalid `prisma.test.findUnique()` invocation in
    /Users/jkomyno/work/prisma/prisma/sandbox/basic-sqlite/index.ts:15:34
    
      12 console.log(user)
      13 
      14 // Add your code using Prisma Client
    → 15 const test = await prisma.test.findUnique({
           where: {
             userId: 1,
         ?   id?: Int,
         ?   AND?: TestWhereInput | TestWhereInput[],
         ?   OR?: TestWhereInput[],
         ?   NOT?: TestWhereInput | TestWhereInput[],
         ?   createdAt?: DateTimeFilter | DateTime,
         ?   updatedAt?: DateTimeFilter | DateTime,
         ?   score?: IntFilter | Int,
         ?   user?: UserRelationFilter | UserWhereInput
           },
           select: {
             score: true
           }
         })
    
    Argument `where` of type TestWhereUniqueInput needs at least one of `id` or `Test_userId_unique_constraint` arguments. Available options are marked with ?.
    

@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 May 30, 2024
@janpio janpio changed the title Runtime error that occurs in findunique() when unique constraint is composed of one field Runtime error that occurs in findUnique() when unique constraint is composed of one field May 30, 2024
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. domain/client Issue in the "Client" domain: Prisma Client, Prisma Studio etc. kind/bug A reported bug. topic: typescript topic: validation
Projects
None yet
Development

No branches or pull requests

3 participants