language-tools icon indicating copy to clipboard operation
language-tools copied to clipboard

@@index not works for multiple keys

Open chhornponleu opened this issue 2 years ago • 3 comments

Sample schema

...

datasource db {
  provider     = "mysql"
  url          = env("DATABASE_URL")
  relationMode = "prisma"
}

model User {
  id            String          @id @default(cuid())
  firstName     String?
  middleName    String
  gender        String?         @db.VarChar(10)
}

model Company {
  id   String @id @default(cuid())
  name String

  createdDate DateTime
  owners      CompanyOwners[] 
}

model CompanyOwners {
  companyId String
  userId    String
  company   Company @relation(fields: [companyId], references: [id])
  user      User    @relation(fields: [userId], references: [id])

  @@id([companyId, userId])
  @@index([userId, companyId])
}

VS Code complain

image

The complain goes away when I use two @@index like

model CompanyOwners {
  companyId String
  userId    String
  company   Company @relation(fields: [companyId], references: [id])
  user      User    @relation(fields: [userId], references: [id])

  @@id([companyId, userId])
  @@index([userId])
  @@index([companyId])
}

chhornponleu avatar Dec 16 '22 14:12 chhornponleu

@@index([companyId, userId]) would be a different index, but it should work to resolve the warning. (note the order of the fields — it matters)

tomhoule avatar Dec 16 '22 15:12 tomhoule

@chhornponleu The index you have only lists the companyId as the second part, which means it can not be used to optimize JOINs based on the companyId column.

Shouldn't this case be covered by the compound primary key with companyId as the first field/column though already @tomhoule?

janpio avatar Dec 16 '22 15:12 janpio

Good catch, it should, looks like a bug.

tomhoule avatar Dec 16 '22 16:12 tomhoule