TypeError: Seems like the schema generic is missing - did you forget to add it to your DB type?

How can I solve the following generic error relating to the db.query.users in my code below?
Property 'users' does not exist on type 'DrizzleTypeError<"Seems like the schema generic is missing - did you forget to add it to your DB type?"> | { [x: string]:RelationalQueryBuilder<ExtractTablesWithRelations<any>, { ...; }>; }'. 

Property 'users' does not exist on type 'DrizzleTypeError<"Seems like the schema generic is missing - did you forget to add it to your DB type?">'.ts(2339)


I'm trying to create an adapter that accepts a generic schema to instantiate a PostgresJsDatabase instance, or colloquially
db
.

I've created the schema that is needed for this adapter, but how can I satisfy typescript when running db.query.user.findFirst()?

import { PostgresJsDatabase, drizzle } from "drizzle-orm/postgres-js";
import { Sql } from "postgres";
import * as schema from "./schema";
import { eq } from "drizzle-orm";

export function postgresAdapter<T extends typeof schema = any>(
  sql: Sql,
  schema: T
) {
  const db = drizzle(sql, { schema });

  const { users } = schema;

  // This function works below
  async function insertUser(
    user: typeof users.$inferInsert
  ): Promise<void> {
    await db
      .insert(users)
      .values(user)
      .onConflictDoNothing({ target: users.id });
  }

  // I'm getting an error here at db.query
  async function getUserById(
    id: string
  ): Promise<typeof schema.users.$inferSelect | null> {
    const user = await db.query.users.findFirst({
                               ^ // Property 'users' does
                                 // not exist on type
      where: (users: any, { eq }) => eq(users.id, id),
     });
    return user || null;
  }
}
Was this page helpful?