drizzle-team / drizzle-orm

Headless TypeScript ORM with a head. Runs on Node, Bun and Deno. Lives on the Edge and yes, it's a JavaScript ORM too πŸ˜…
https://orm.drizzle.team
Apache License 2.0
24.02k stars 606 forks source link

[BUG]: TypeError: Object literal may only specify known properties #2619

Open fn3x opened 3 months ago

fn3x commented 3 months ago

What version of drizzle-orm are you using?

0.32.0

What version of drizzle-kit are you using?

0.23.0

Describe the Bug

I bumped the versions of drizzle-orm 0.31.4 -> 0.32.0 and drizzle-kit 0.22.8 -> 0.23.0. After that my project stopped from building because some of the columns are not being recognized by the type system. I provided the error log, table definition and code that uses it below.

TS compiler error log:

src/services/sessions/index.ts:31:8 - error TS2769: No overload matches this call.
  Overload 1 of 2, '(value: { currency: string | SQL<unknown> | Placeholder<string, any>; platformType: number | SQL<unknown> | Placeholder<string, any>; sessionId: string | SQL<...> | Placeholder<...>; playerId: number | ... 1 more ... | Placeholder<...>; startTime: string | ... 1 more ... | Placeholder<...>; partnerTokenId: number | ... 1 more ... | Placeholder<...>; partnerSessionId: string | ... 1 more ... | Placeholder<...>; }): MySqlInsertBase<...>', gave the following error.
    Object literal may only specify known properties, and 'isUsed' does not exist in type '{ currency: string | SQL<unknown> | Placeholder<string, any>; platformType: number | SQL<unknown> | Placeholder<string, any>; sessionId: string | SQL<unknown> | Placeholder<...>; playerId: number | ... 1 more ... | Placeholder<...>; startTime: string | ... 1 more ... | Placeholder<...>; partnerTokenId: number | ... ...'.
  Overload 2 of 2, '(values: { currency: string | SQL<unknown> | Placeholder<string, any>; platformType: number | SQL<unknown> | Placeholder<string, any>; sessionId: string | SQL<...> | Placeholder<...>; playerId: number | ... 1 more ... | Placeholder<...>; startTime: string | ... 1 more ... | Placeholder<...>; partnerTokenId: number | ... 1 more ... | Placeholder<...>; partnerSessionId: string | ... 1 more ... | Placeholder<...>; }[]): MySqlInsertBase<...>', gave the following error.
    Object literal may only specify known properties, and 'sessionId' does not exist in type '{ currency: string | SQL<unknown> | Placeholder<string, any>; platformType: number | SQL<unknown> | Placeholder<string, any>; sessionId: string | SQL<unknown> | Placeholder<...>; playerId: number | ... 1 more ... | Placeholder<...>; startTime: string | ... 1 more ... | Placeholder<...>; partnerTokenId: number | ... ...'.

31       .values({

Table definition in schema.ts:

export const playersAuthSessions = mysqlTable("players_auth_sessions", {
    id: int("id").autoincrement().notNull(),
    sessionId: varchar("sessionId", { length: 40 }).notNull(),
    playerId: int("playerId").notNull(),
    currency: varchar("currency", { length: 4 }).notNull(),
    platformType: int("platformType").notNull(),
    startTime: datetime("startTime", { mode: 'string'}).notNull(),
    endTime: datetime("endTime", { mode: 'string'}),
    isActive: tinyint("isActive"),
    isUsed: tinyint("isUsed"),
    partnerTokenId: int("partnerTokenId").notNull(),
    partnerSessionId: varchar("partnerSessionId", { length: 64 }).notNull(),
    playerAddress: varchar("playerAddress", { length: 64 }),
    httpCFIPCountry: varchar("httpCFIPCountry", { length: 2 }),
    httpCFCoordinates: varchar("httpCFCoordinates", { length: 64 }),
},
(table) => {
    return {
        sessionId: index("sessionId").on(table.sessionId),
        playerId_idx: index("playerId_idx").on(table.playerId),
        players_auth_sessions_id: primaryKey({ columns: [table.id], name: "players_auth_sessions_id"}),
        sessionId_UNIQUE: unique("sessionId_UNIQUE").on(table.sessionId),
    }
});

Usage of table to perform queries:

    import { partners, partnersTokens, players, playersAuthSessions } from "../../schema"

    const session = {
      playerId: request.body.player.id,
      currency: request.body.player.currency,
      platformType: +request.body.settings.platform.type,
      sessionId: uuidv4(),
      partnerTokenId: request.tokenId,
      partnerSessionId: request.body.player.session.sid,
      startTime: DateTime.now().toUTC().toSQL({ includeOffset: false })
    }

    await this.db.insert(playersAuthSessions)
      .values({
        sessionId: session.sessionId,
        playerId: session.playerId,
        platformType: session.platformType,
        partnerSessionId: session.partnerSessionId,
        partnerTokenId: session.partnerTokenId,
        currency: session.currency,
        startTime: session.startTime,
        isUsed: 0,
        isActive: 0
      })

Expected behavior

All specified columns being recognized by the type system on writing queries

Environment & setup

Node.js v20.12.2 drizzle-kit v0.32.0 drizzle-orm v0.23.0

marko1010 commented 3 months ago

I can confirm this happens with 0.32.0. If you add .notNull() to the column declaration the error disappears

jberns commented 3 months ago

Was testing out drizzle for the first time today and ran into this issue on a fresh install trying to figure out what was wrong. Downgraded to 0.31.4 based on @marko1010 's comment and it resolved the type issues for now.

antonjlin commented 3 months ago

Can confirm am also getting this issue with node-pg on 0.32.0

jamaluddinrumi commented 3 months ago

update drizzle-orm to v0.32.1

can confirm that it's already solved

can safely remove

- "resolutions": {
-   "drizzle-orm": "0.31.4"
- }

from my package.json starts from now

kudos drizzle team πŸŽ‰

aXenDeveloper commented 3 months ago

I have still this issue on drizzle-orm@0.32.1 and drizzle-kit@0.23.0 :<

fn3x commented 3 months ago

I have still this issue on drizzle-orm@0.32.1 and drizzle-kit@0.23.0 :<

Yep, I have this issue still on drizzle-orm@0.32.1

jamaluddinrumi commented 3 months ago

I have still this issue on drizzle-orm@0.32.1 and drizzle-kit@0.23.0 :<

Yep, I have this issue still on drizzle-orm@0.32.1

ya, i experienced this again, and i don't know why

end up to add these again to my package.json.

+ "resolutions": {
+    "drizzle-orm": "0.31.4"
+ }
ntnz commented 2 months ago

I am also experiencing this issue on 0.32.1

aXenDeveloper commented 2 months ago

It looks like now drizzle-orm@0.32.0+ requires in tsconfig.json set strictNullChecks and strict to true.

QuangPhamvt commented 2 months ago

:>> when they fix it :????

Ymirke commented 2 months ago

Had the same issue with:

"drizzle-kit": "^0.24.0",
"drizzle-orm": "^0.33.0",

Tested following fixes in this thread:

fnoori commented 2 months ago

A little unrelated but getting the same error when doing a nested query; isVerified: true was giving me the error.

Adding the strict and strictNullChecks didn't work for me. I ended just casting it to any like:

db.query.products.findMany({
  where: ...,
  with: {
    user: {
      isVerified: true, // This is where I was getting the error
      columns: { password: false }
      ...
    } as any
  }
})
fn3x commented 2 months ago

Had the same issue with:

"drizzle-kit": "^0.24.0",
"drizzle-orm": "^0.33.0",

Tested following fixes in this thread:

  • Adding notNull to table column:

    • Fixes the error, but then as expected I'm getting errors where I'm not using the column.
  • Resolutions does not do anything for me.
  • Adding strict null checks fixed it for me.

Update: it did fix! thanks!

Sadly, it didn't fix it for me:

    const insertId = await this.db.insert(players).values({
      userId: playerData.uid,
      firstname: playerData.firstname,
      lastname: playerData.lastname,
      nickname: playerData.nickname,
      language: playerData.language,
    }).then(res => res[0].insertId)

typescript: No overload matches this call. β”‚ β”‚ Overload 2 of 2, '(values: { partnerId: number | SQL | Placeholder<string, any>; userId: string | SQL<uβ”‚ β”‚ nknown> | Placeholder<string, any>; status: number | SQL | Placeholder<...>; ... 8 more ...; updatedAt?β”‚ β”‚ : string | ... 3 more ... | undefined; }[]): MySqlInsertBase<...>', gave the following error. β”‚ β”‚ Object literal may only specify known properties, and 'userId' does not exist in type '{ partnerId: number | Sβ”‚ β”‚ QL | Placeholder<string, any>; userId: string | SQL | Placeholder<string, any>; status: numbβ”‚ β”‚ er | SQL | Placeholder<...>; ... 8 more ...; updatedAt?: string | ... 3 more ... | undefined; }[]'

fn3x commented 2 months ago

So the issue is still relevant but @Ymirke found out a workaround

waza-ari commented 2 months ago

Same issue here. Adding strict null checks is not an option for many existing code bases (although I agree its better to fix those potential type errors, but there'll be many code bases out there that won't be able to accommodate that). In my case, I needed to

Are there plans to tackle this issue?

cristiano-linvix commented 1 month ago

It looks like now drizzle-orm@0.32.0+ requires in tsconfig.json set strictNullChecks and strict to true.

insert into compilerOptions works for me, thanks!

cristiano-linvix commented 1 month ago

But other things started to bother me in TypeScript.

Now null strings are no longer allowed without defining string | null

This is really annoying...

teneburu commented 2 weeks ago

I have the issue with "drizzle-kit": "^0.25.0", "drizzle-orm": "^0.34.1", even with "strictNullChecks": true, "strict": true, 😭

HNOONa-0 commented 1 week ago

It looks like now drizzle-orm@0.32.0+ requires in tsconfig.json set strictNullChecks and strict to true.

This fixed the issue for me. Could you please elaborate why that is related? I was trying to update field of a user table but TypeScript complained about most attributes that I tried to edit. How is this related?

AbhayBhan commented 6 days ago

I was getting the same error. And even after adding the tsconfig changes, the Nest application was failing at build. I assumed that maybe... when the update query is being ran for a field, it is not able to determine if the row actually exists in the Database or not. Hence there is an SQLUnknown in the the type def. I don't know how accurate i am with this but it seems to have worked :

`async addBalance(amount : number, id : string) { try { if(amount < 0) { throw new HttpException('Invalid amount', HttpStatus.BAD_REQUEST); }

  const userAccount = await db.query.AccountTable.findFirst({
    where: eq(AccountTable.userId, id)
  });

  if(!userAccount) {
    throw new HttpException('Account not Found.', HttpStatus.BAD_REQUEST);
  }

  userAccount.balance += amount;

  await db.update(AccountTable).set(userAccount).where(eq(AccountTable.userId, id));

  // This line was giving me the same problem.
  // await db.update(AccountTable).set({ balance: amount }).where(eq(AccountTable.userId, id));

  return { message : "Successfully added balance" };
} catch (error) {
  if (error instanceof HttpException) {
    throw error;
  }
  throw new HttpException(
    'Failed to register user',
    HttpStatus.INTERNAL_SERVER_ERROR,
  );
}

} `

Though I do feel this adds one extra query. But this seemed to be the only solution I could devise. Hope it helps someone.

Also, After adding this I could turn back the tsconfig changes, so less headache while developing yay.

"drizzle-orm": "^0.33.0"

carbdias commented 4 days ago

hello, I have this config

import { defineConfig } from "drizzle-kit";

export default defineConfig({
    schema:"./src/db/schema.ts",
    out: "./src/db/migrations",
    dialect: "sqlite",
    driver: "d1-http",
    strictNullChecks : true,
    strict: true,
    dbCredentials: {
        url: "file:./src/db/sqlite.db",
    },
});

And I'm having the error in the url inside of the dbCredentials :

Object literal may only specify known properties, and 'url' does not exist in type '{ accountId: string; databaseId: string; token: string; }'.ts(2353) (property) url: string

Any idea on what can be wrong ??

Thank you in advance,

AbhayBhan commented 4 days ago

Seems like you are getting this error because of a bad config, though everything does look right right to me. Drizzle is always updating and changing these things so I suggest you to take a good look through docs : https://orm.drizzle.team/docs/get-started/sqlite-new

carbdias commented 3 days ago

Thank you, Actually I get this path error but I can run the drizzle-kit generate command, it creates the migrations folder with content.

However, if I try to use the command migrate, or push, I get this error :

$ npx drizzle-kit migrate No config path provided, using default 'drizzle.config.ts' Reading config file 'C:\Users\chicn\OneDrive\Ambiente de Trabalho\Personal code Projects 2024\code 2024\Node18\receitas\drizzle.config.ts' Error Please provide required params for D1 HTTP driver: [x] accountId: undefined [x] databaseId: undefined [x] token: undefined

Any idea on how to solve this?

I'm just working with an sqlite database file with no credentials on it yet.

cargemini commented 3 days ago

It seems that the problem was that I was defining a driver, when I'm actually working locally. Removing this prop solved the issue of url does not exist in type, and the params for D1 HTTP driver missing. The only warning that persists it seems to be the path. But it seems it doesn't have a negative effect on drizzle commands.

Thank you for the reply !

carbdias commented 3 days ago

Thank, I'm loving working with Drizzle-kit until now. I would just love to know if there is a way to remove the ascii chars that appear in the middle of the messages for color. I've tried to deactivate them using the NO_COLOR variable, it didn't work, and trying other terminals such as powershell. Maybe there is another way, but I didn't find it yet.

example : Drizzle Studio is up and running on ←[34mhttps://local.drizzle.studio←[39m

Thank tou for the good work !