prisma / prisma

Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB
https://www.prisma.io
Apache License 2.0
39.6k stars 1.54k forks source link

Issues with model/type generation after changing User -> id to a string, and adding a username on session creation #18866

Open ameshkin opened 1 year ago

ameshkin commented 1 year ago

Bug description

Hello everyone, I was asked to report this bug, I was able to fix by manually overriding my models that are generated.

I wanted to change the id of the User model from a number to a string, and also add a username that will be used in other tables.

export type User = {
  id: any // 

The fix was applying was updating types.ts, but this is a bug since we shouldn't have to manually correct. I also removed the username I was trying to put into sessions, and turned the userId back into a number instead of a string.

There is someone else having the same issue, but put his bug report into the blitz page. I believe this is a prisma issue. https://github.com/blitz-js/blitz/issues/3883

Also, I am using provider = "mysql" and not sqlite. Perhaps this makes a difference.

declare module "@blitzjs/auth" {
  export interface Session {
    isAuthorized: SimpleRolesIsAuthorized<Role>
    PublicData: {
      userId: string
      // userId: User["id"]
      role: Role
      username: string
    }
  }
}

These are some of the types of errors I receive on mutations. I have tried different types to get this working, but am pretty new to typescript.

   const site = await db.site.create({ data: input })

# causes these errors
      Types of property 'userId' are incompatible.
        Type 'string' is not assignable to type 'never'.

This is the error I am getting on build.

error TS2345: Argument of type 'PrismaClient<PrismaClientOptions, unknown, RejectOnNotFound | RejectPerOperation> & EnhancedPrismaClientAddedMethods' is not assignable to parameter of type 'PrismaClientWithSession'.
  The types of 'session.create' are incompatible between these types.
    Type '<T extends SessionCreateArgs>(args: SelectSubset<T, SessionCreateArgs>) => Prisma__SessionClient<SessionGetPayload<T>, never>' is not assignable to type '(args: { data: SessionModel & { userId?: any; user?: { connect: { id: any; }; }; }; }) => Promise<SessionModel>'.
      Types of parameters 'args' and 'args' are incompatible.
        Type '{ data: SessionModel & { userId?: any; user?: { connect: { id: any; }; }; }; }' is not assignable to type '{ select?: SessionSelect; include?: SessionInclude; data: (Without<SessionCreateInput, SessionUncheckedCreateInput> & SessionUncheckedCreateInput) | (Without<...> & SessionCreateInput); }'.
          Types of property 'data' are incompatible.
            Type 'SessionModel & { userId?: any; user?: { connect: { id: any; }; }; }' is not assignable to type '(Without<SessionCreateInput, SessionUncheckedCreateInput> & SessionUncheckedCreateInput) | (Without<...> & SessionCreateInput)'.
              Type 'SessionModel & { userId?: any; user?: { connect: { id: any; }; }; }' is not assignable to type 'Without<SessionUncheckedCreateInput, SessionCreateInput> & SessionCreateInput'.
                Type 'SessionModel & { userId?: any; user?: { connect: { id: any; }; }; }' is not assignable to type 'Without<SessionUncheckedCreateInput, SessionCreateInput>'.
                  Types of property 'userId' are incompatible.
                    Type 'any' is not assignable to type 'never'.

46       storage: PrismaStorage(db),

How to reproduce

Expected behavior

Expected behavior would be for prisma to generate and update models correctly.

Prisma information

My models

model User {
  id             String         @id @default(uuid())
  createdAt      DateTime       @default(now())
  updatedAt      DateTime       @updatedAt
  username       String         @unique
  name           String?
  email          String         @unique
  emailVerified  DateTime?
  image          String?
  balance        Int?
  hashedPassword String?
  role           String         @default("USER")
  level          String?
  Accounts       Account[]
  Sessions       Session[]
  Files          File[]
  Activities     Activity[]
  Messages       Message[]
  Notifications  Notification[]
  Customers      Customer[]
  Links          Links[]
  Site           Site[]
  Profile        Profile[]
  Token          Token[]
}

model Profile {
  id          String   @id @default(cuid())
  userId      String
  title       String
  username    String   @unique. // SAME AS IN USER
  description String?
  theme       Json?
  widgets     Json?
  current     Yesno    @default(no)
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt
  user        User     @relation(fields: [userId], references: [id])
  Site        Site[]
}
export type User = {
  id: any // FIXME: THIS FIXES THIS ERROR, REMOVING WILL BREAK AGAIN
  createdAt: Date
  updatedAt: Date
  username: string
  name: string | null
  email: string
  emailVerified: Date | null
  image: string | null
  balance: number | null
  hashedPassword: string | null
  role: string
  level: string | null
}

declare module "@blitzjs/auth" {
  export interface Session {
    isAuthorized: SimpleRolesIsAuthorized<Role>
    PublicData: {
      userId: User["id"]
      role: Role
      username: string
    }
  }
}

Environment & setup

Prisma Version

PRISMA VERSIONS THAT WERE TRIED 4.13.0

4.12.0

4.11.0

I made sure prisma and prisma client matched.

ameshkin commented 1 year ago

I was able to fix a similar issue before but am having this issue again.

This time I am trying to set publicData in the Session table manually. I have to do this without $ctx or the blitz auth since it's in a webhook. I want to change a user session.

I can use ts-ignore and get past it, and the site functions and works well after I change publicData.

I have tried publicData: any in types.ts but it's not working. However, this is what fixed my issue with the userId field.

// <html>TS2345: Argument of type 'PrismaClient&lt;PrismaClientOptions, unknown, Args&gt; &amp; EnhancedPrismaClientAddedMethods' is not assignable to parameter of type 'PrismaClientWithSession'.<br/>The types of 'session.update' are incompatible between these types.<br/>Type '&lt;T extends SessionUpdateArgs&lt;Args&gt;&gt;(args: SelectSubset&lt;T, SessionUpdateArgs&lt;Args&gt;&gt;) =&gt; Prisma__SessionClient&lt;GetFindResult&lt;SessionPayload&lt;Args&gt;, T&gt;, never, Args&gt;' is not assignable to type '(args: { data: Partial&lt;SessionModel&gt;; where: { handle?: string | undefined; }; }) =&gt; Promise&lt;SessionModel&gt;'.<br/>Types of parameters 'args' and 'args' are incompatible.<br/>Type '{ data: Partial&lt;SessionModel&gt;; where: { handle?: string | undefined; }; }' is not assignable to type '{ select?: SessionSelect&lt;Args&gt; | null | undefined; include?: SessionInclude&lt;Args&gt; | null | undefined; data: (Without&lt;SessionUpdateInput, SessionUncheckedUpdateInput&gt; &amp; SessionUncheckedUpdateInput) | (Without&lt;...&gt; &amp; SessionUpdateInput); where: SessionWhereUniqueInput; }'.<br/>Types of property 'where' are incompatible.<br/>Type '{ handle?: string | undefined; }' is not assignable to type 'SessionWhereUniqueInput'.<br/>Type '{ handle?: string | undefined; }' is not assignable to type '{ id: string | number; handle: string | number; userId: string | number; } &amp; { id?: number | undefined; handle?: string | undefined; userId?: number | undefined; AND?: SessionWhereInput | SessionWhereInput[] | undefined; ... 9 more ...; user?: (Without&lt;...&gt; &amp; UserWhereInput) | ... 1 more ... | undefined; }'.<br/>Type '{ handle?: string | undefined; }' is missing the following properties from type '{ id: string | number; handle: string | number; userId: string | number; }': id, userId
> prisma -v
Environment variables loaded from .env
prisma                  : 5.0.0
@prisma/client          : 5.0.0
Current platform        : darwin-arm64
Query Engine (Node-API) : libquery-engine 6b0aef69b7cdfc787f822ecd7cdc76d5f1991584 (at node_modules/@prisma/engines/libquery_engine-darwin-arm64.dylib.node)
Schema Engine           : schema-engine-cli 6b0aef69b7cdfc787f822ecd7cdc76d5f1991584 (at node_modules/@prisma/engines/schema-engine-darwin-arm64)
Schema Wasm             : @prisma/prisma-schema-wasm 4.17.0-26.6b0aef69b7cdfc787f822ecd7cdc76d5f1991584
Default Engines Hash    : 6b0aef69b7cdfc787f822ecd7cdc76d5f1991584
Studio                  : 0.487.0
ameshkin commented 1 year ago

I also want to add, that this is the code that started this issue publicDataNew is a json string, since publicData is set to string.

Perhaps it should just be a JSON type. To reiterate, the query does work and update the table and session. Just gives a build error.

        const updateUserSession = await db.session.update({
            where: { userId: user.id },
            data: { publicData: publicDataNew },
          })