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.

uncheckedScalarInputs: XOR not working?

See original GitHub issue

Bug description

The XOR functionality to allow either unchecked scalars xor regular prisma relations doesn’t appear to be working for me

the function:

export const createInvestor = ({ input: { companyId, email } }) => {
  return db.investor.create({
    data: {
      company: {
        connect: { id: companyId },
      },
      investor: {
        connectOrCreate: {
          where: { email },
          create: { email },
        },
      },
    },
  })
}

the error:

api | Error:
api | Invalid `prisma.investor.create()` invocation:
api |
api | {
api |   data: {
api |     company: {
api |     ~~~~~~~
api |       connect: {
api |         where: {
api |           companyId: 'dc7085fb-62e0-405c-bb0f-a4d33fa6bcae'
api |         }
api |       }
api |     },
api |     investor: {
api |     ~~~~~~~~
api |       connectOrCreate: {
api |         where: {
api |           email: 'test@gmail.com'
api |         },
api |         create: {
api |           email: 'test@gmail.com'
api |         }
api |       }
api |     },
api | +   investorId: String,
api | +   companyId: String,
api | ?   createdAt?: DateTime,
api | ?   updatedAt?: DateTime
api |   }
api | }
api |
api | Unknown arg `company` in data.company for type InvestorUncheckedCreateInput. Did you mean `companyId`?
api | Unknown arg `investor` in data.investor for type InvestorUncheckedCreateInput. Did you mean `investorId`?
api | Argument investorId for data.investorId is missing.
api | Argument companyId for data.companyId is missing.

Expected behavior

Prisma should recognize I’m not using unchecked scalars

Prisma information

model Investor {
  investor    User  @relation(fields: [investorId], references: [id])
  investorId    String
  company    Company  @relation(fields: [companyId], references: [id])
  companyId    String
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  @@id([investorId, companyId])
}

Environment & setup

  • OS: MacOS 10.15.5
  • Database: Postgres 12.5
  • Node.js version: 14.15.4
  • Prisma version: 2.11.0 [used through redwoodjs]
  • Redwood version: 0.23

Happy to provide further information if helpful, have not yet tried to re-create in a minimal repo

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:26 (5 by maintainers)

github_iconTop GitHub Comments

5reactions
thrantcommented, Jan 29, 2021

I just upgraded to 2.15 and Creates & Updates that were previously working started hitting the types <type>Unchecked<Create/Update>Input instead of expected <type><Create/Update>Input (so for example ContactPersonUncheckedUpdateInput when I’m providing data that matches ContactPersonUpdateInput.)

At first I though I had the same issue, but turns out it was actually an error on my part, causing to a bit misleading error message! So read further to check if that’s the case with you as well

Here’s some details.

prisma.schema:

model Company {
  id            Int             @id @default(autoincrement()) @db.Int
  <other-data>
}

model ContactPerson {
  id          String        @id @db.VarChar(191)
  <other-data>

  companyId   Int?          @db.Int
  Company     Company?      @relation(fields: [companyId], references: [id])
  @@index([companyId], name: "companyId")

  SubContract SubContract[]
}

Log

  create: {
    id: '18864',
    <other-data>
    Company: {
    ~~~~~~~
      connect: {
        id: '12345'
      }
    },
+   updatedAt: DateTime,
?   createdAt?: DateTime,
?   companyId?: Int | null,
?   SubContract?: {
?     create?: SubContractCreateWithoutContactPersonInput | SubContractCreateWithoutContactPersonInput | SubContractUncheckedCreateWithoutContactPersonInput | SubContractUncheckedCreateWithoutContactPersonInput,
?     connect?: SubContractWhereUniqueInput | SubContractWhereUniqueInput,
?     connectOrCreate?: SubContractCreateOrConnectWithoutContactPersonInput | SubContractCreateOrConnectWithoutContactPersonInput
?   },
...
  }
}

Unknown arg `Company` in update.Company for type ContactPersonUncheckedUpdateInput. Did you mean `companyId`?

prisma client index.ts:

export type ContactPersonCreateArgs = {
   ....
  data: XOR<ContactPersonUncheckedCreateInput, ContactPersonCreateInput>
}

  export type ContactPersonCreateInput = {
    id: string
    <other-data>
    Company?: CompanyCreateOneWithoutContactPersonsInput
    SubContract?: SubContractCreateManyWithoutContactPersonInput
  }

  export type ContactPersonUncheckedCreateInput = {
    id: string
    <other-data>
    companyId?: number | null
    SubContract?: SubContractUncheckedCreateManyWithoutContactPersonInput
  }

  export type CompanyCreateOneWithoutContactPersonsInput = {
    create?: XOR<CompanyUncheckedCreateWithoutContactPersonsInput, CompanyCreateWithoutContactPersonsInput>
    connect?: CompanyWhereUniqueInput
    connectOrCreate?: CompanyCreateOrConnectWithoutContactPersonsInput
  }

  export type CompanyWhereUniqueInput = {
    id?: number
  }

…but what had really happened that I had just refactored the Company ID to be Int instead of String, but was still providing a String in one place - causing the XOR to not match ContactPersonCreateInput, and fall back to the ContactPersonUncheckedCreateInput, leaving me on a goose hunt googling, finding this error and thinking I had the same case. 😄

So changing the prisma.create call’s data from String Company = { connect: '12345' } to number (as expected in CompanyWhereUniqueInput) Company = { connect: 12345 } caused the XOR to match the correct input type, and fixed the matter for me.

So, in case you encounter this error double check that you’re feeding the exactly right types first, since the error message is currently bit misleading.

3reactions
jagoncalves14commented, Apr 8, 2021

Hi @timsuchanek!

I think I’m running with this exact same issue.

This is the error I get when I try to create a Post. image

Weirdly enough, I’m able to Update a post with categories, but can’t Create.

Here are the informations related to the Create Post:

Create Post

Types in Prisma’s index.d.ts:

export type PostCreateInput = {
    createdAt?: Date | string
    published?: boolean
    title: string
    content?: string
    author: UserCreateNestedOneWithoutPostsInput
    categories?: CategoryCreateNestedManyWithoutPostsInput
    tags?: TagCreateNestedManyWithoutPostsInput
}

export type PostUncheckedCreateInput = {
    id?: number
    createdAt?: Date | string
    authorId: number
    published?: boolean
    title: string
    content?: string
}

Mutation:

const CreatePost = z
  .object({
    title: z.string(),
    content: z.string(),
    published: z.boolean(),
    categories: z.array(
      z.object({
        name: z.string(),
        id: z.number().int(),
      }),
    ),
  })
  .nonstrict()

export default resolver.pipe(
  resolver.zod(CreatePost),
  resolver.authorize(),
  async ({id, ...data}) => {
    const payload = {
      ...data,
      categories: {
        connectOrCreate: data.categories.map((cat) => ({
          where: {id: cat.id},
          create: {
            name: cat.name,
          },
        })),
      },
    }

    return await db.post.create({
      data: payload,
    })
  },
)

Update Post

Types in Prisma’s index.d.ts:

export type PostUpdateInput = {
    createdAt?: DateTimeFieldUpdateOperationsInput | Date | string
    published?: BoolFieldUpdateOperationsInput | boolean
    title?: StringFieldUpdateOperationsInput | string
    content?: StringFieldUpdateOperationsInput | string
    author?: UserUpdateOneRequiredWithoutPostsInput
    categories?: CategoryUpdateManyWithoutPostsInput
    tags?: TagUpdateManyWithoutPostsInput
}

export type PostUncheckedUpdateInput = {
    id?: IntFieldUpdateOperationsInput | number
    createdAt?: DateTimeFieldUpdateOperationsInput | Date | string
    authorId?: IntFieldUpdateOperationsInput | number
    published?: BoolFieldUpdateOperationsInput | boolean
    title?: StringFieldUpdateOperationsInput | string
    content?: StringFieldUpdateOperationsInput | string
}

Mutation:

const UpdatePost = z
  .object({
    id: z.number().int(),
    title: z.string(),
    content: z.string(),
    published: z.boolean(),
    categories: z.array(
      z.object({
        name: z.string(),
        id: z.number().int(),
      }),
    ),
  })
  .nonstrict()

export default resolver.pipe(
  resolver.zod(UpdatePost),
  resolver.authorize(),
  async ({id, ...data}) => {
    delete data.authorId

    const payload = {
      ...data,
      categories: {
        set: [],
        connectOrCreate: data.categories.map((cat) => ({
          where: {id: cat.id},
          create: {
            name: cat.name,
          },
        })),
      },
    }

    return await db.post.update({where: {id}, data: payload})
  },
)

And here is the Model Schema:

model Post {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  authorId  Int
  published Boolean  @default(false)
  title     String
  content   String   @default("")

  author     User       @relation(fields: [authorId], references: [id])
  categories Category[]
  tags       Tag[]
}

model Category {
  id   Int    @id @default(autoincrement())
  name String

  posts Post[]
}

I can’t understand why this is working in Update and not on Create when both Types are the same regarding to the categories field. Maybe I’m doing something obviously wrong. Can someone help me out?

Read more comments on GitHub >

github_iconTop Results From Across the Web

XOR output is wrong in Javascript - node.js - Stack Overflow
In response to your edit, when working with integers and Number , you need to ensure that your values do not exceed Number....
Read more >
prisma/prisma 2.18.0 on GitHub - NewReleases.io
uncheckedScalarInputs : XOR not working? Query produces WHERE clause with 1=0 as condition · User ID type instead of int to enable database ......
Read more >
@prisma/cli: Versions | Openbase
The reason for this is that a number of users were experiencing issues when running the npx prisma command. Without a local installation...
Read more >
That XOR Trick
Before we solve the problem of finding the missing number, let's start with this simpler problem: Swap two values x and y in-place,...
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