postgresql 如何使用schema初始化Drizzle ORM客户端?

q5iwbnjs  于 2023-10-18  发布在  PostgreSQL
关注(0)|答案(1)|浏览(139)

我有一个实体

// schema.ts
export const users = pgTable('users', {
  id: serial('id').primaryKey(),
  email: varchar('email', {length: 256}).notNull(),
});

然后我试着初始化毛毛雨客户端

// db.server.ts
import {PostgresJsDatabase, drizzle} from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import * as schema from './schema';

const queryClient = postgres("postgres://...");
const db: PostgresJsDatabase = drizzle(queryClient, {schema});

其中VS Code开始抱怨{schema}部分,并出现以下错误:

Type 'PostgresJsDatabase<typeof import("/app/db/schema")>' is not assignable to type 'PostgresJsDatabase'.
  The types of '_.schema' are incompatible between these types.
    Type 'ExtractTablesWithRelations<typeof import(/app/db/schema")> | undefined' is not assignable to type 'ExtractTablesWithRelations<Record<string, never>> | undefined'.
      Type 'ExtractTablesWithRelations<typeof import("/app/db/schema")>' is not assignable to type 'ExtractTablesWithRelations<Record<string, never>>'.
        Property 'users' is incompatible with index signature.
          Type '{ tsName: "users"; dbName: "users"; columns: { id: PgColumn<{ name: "id"; tableName: "users"; dataType: "number"; columnType: "PgSerial"; data: number; driverParam: number; notNull: true; hasDefault: true; enumValues: undefined; baseColumn: never; }, {}, {}>; email: PgColumn<...>; }; relations: never; primaryKey: An...' is not assignable to type '{ tsName: string; dbName: never; columns: never; relations: Record<string, Relation<string>>; primaryKey: AnyColumn[]; }'.
            Types of property 'dbName' are incompatible.
              Type 'string' is not assignable to type 'never'.ts(2322)

我从来没有和Typescript交过朋友(我还在尝试),所以我不知道出了什么问题。在例子中他们是这样做的…有什么建议吗?
如果我把{schema}部分去掉的话,这也可以正常工作,但是我想我需要它来使用我想要使用的db.query.users.findMany()语法?

wyyhbhjk

wyyhbhjk1#

db const的类型转换是错误的。它缩小了范围。因此,删除PostgresJsDatabase强制转换可以解决问题。

相关问题