drizzle-orm icon indicating copy to clipboard operation
drizzle-orm copied to clipboard

[BUG]: PgTable types don't work well when come from generics

Open MatanYadaev opened this issue 8 months ago β€’ 3 comments

Report hasn't been filed before.

  • [x] I have verified that the bug I'm about to report hasn't been filed before.

What version of drizzle-orm are you using?

0.41.0

What version of drizzle-kit are you using?

0.30.6

Other packages

No response

Describe the Bug

I'm trying to make an abstract shared repository (BaseRepository) for all of my tables, but Drizzle's types doesn't like it.

How to reproduce:

// db/index.ts
import 'dotenv/config';
import { drizzle } from 'drizzle-orm/node-postgres';

export const db = drizzle(process.env.DATABASE_URL!);
// db/schema.ts
import { integer, pgTable, varchar } from "drizzle-orm/pg-core";

export const users = pgTable("users", {
  id: integer().primaryKey().generatedAlwaysAsIdentity(),
  name: varchar({ length: 255 }).notNull(),
  age: integer().notNull(),
  email: varchar({ length: 255 }).notNull().unique(),
});
// base-repository.ts
import * as schema from "./schema";
import {db} from "./index";

export class BaseRepository<Table extends typeof schema[keyof typeof schema]> {
    constructor(private readonly table: Table) {}

    async findAll() {
        return await db.select().from(this.table);
        // Error is here              ^
    }
}

This is the error:

Argument of type 'Table' is not assignable to parameter of type 'TableLikeHasEmptySelection<Table> extends true ? DrizzleTypeError<"Cannot reference a data-modifying statement subquery if it doesn't contain a `returning` clause"> : Table'.
  Type 'PgTable<{ name: "users"; schema: undefined; columns: { id: PgColumn<{ name: "id"; tableName: "users"; dataType: "number"; columnType: "PgInteger"; data: number; driverParam: string | number; notNull: true; ... 7 more ...; generated: undefined; }, {}, {}>; name: PgColumn<...>; age: PgColumn<...>; email: PgColumn<...>...' is not assignable to type 'TableLikeHasEmptySelection<Table> extends true ? DrizzleTypeError<"Cannot reference a data-modifying statement subquery if it doesn't contain a `returning` clause"> : Table'.ts(2345)

Expected usage:

// user-repository.ts
import { BaseRepository } from "./base-repository";
import * as schema from "./schema";

export class UserRepository extends BaseRepository<typeof schema.users> {
    constructor() {
        super(schema.users);
    }
}

const userRepository = new UserRepository();
const users = await userRepository.findAll();

MatanYadaev avatar Apr 04 '25 22:04 MatanYadaev

@MatanYadaev I'm facing the same issue.

import { PgTable } from 'drizzle-orm/pg-core'

<S extends PgTable>(source: S, filters: SQL) => {
  return {
    select: db.select().from(source).where(filters).$dynamic(),
    //                       ^ Argument of type 'S' is not assignable to parameter of type 'TableLikeHasEmptySelection<S> extends true ? DrizzleTypeError<"Cannot reference a data-modifying statement subquery if it doesn't contain a `returning` clause"> : S'.
    delete: db.delete(source).where(filters).$dynamic()
  }
}

motherthestate avatar Apr 07 '25 13:04 motherthestate

Hi @MatanYadaev , have you found any workarounds?

rasel-stacklearner avatar Apr 18 '25 13:04 rasel-stacklearner

This is still happening in version 0.43.1.

Haven’t found any fixes for this :/

monopolo11 avatar Apr 27 '25 00:04 monopolo11

Workaround πŸ‘‡

return await db.select().from(this.table as PgTable);

Also, this seems to be happening only with .from() statements, we should edit the issue to be more specific.

fgcoelho avatar May 01 '25 01:05 fgcoelho

I've found that making it an object property works for some reason.

Error

// rqb v1
type TRSchema = ExtractTablesWithRelations<typeof schema>;
// rqb v2
type TRSchema = ExtractTablesWithRelations<typeof relations>;

export class BaseRepository<Table extends TRSchema[keyof TRSchema]["table"]> {
	constructor(private readonly table: Table) {}

	findAll() {
		return db.select().from(this.table);
		// error occurs
	}
}

No Error

// rqb v1
type TRSchema = ExtractTablesWithRelations<typeof schema>;
// rqb v2
type TRSchema = ExtractTablesWithRelations<typeof relations>;

export class BaseRepository<Config extends { table: TRSchema[keyof TRSchema]["table"] }> {
	constructor(private readonly config: Config) {}

	findAll() {
		return db.select().from(this.config.table);
		// no error
	}
}

Then use it like this:

export class UserRepository extends BaseRepository<{ table: typeof users }> {
	constructor() {
		super({ table: users });
	}
}

sillvva avatar May 11 '25 01:05 sillvva

Did anyone solve this?

@sillvva your workaround seems to work for now.

eth0izzle avatar Jun 09 '25 09:06 eth0izzle

Did anyone solve this?

@sillvva your workaround seems to work for now.

I wasn't able to get that workaround working, so I'm just casting to PgTable for now as in https://github.com/drizzle-team/drizzle-orm/issues/4367#issuecomment-2843898404

nathanhleung avatar Jun 19 '25 20:06 nathanhleung

Inspired from @sillvva

This works for me -

base.repository.ts

import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
import { count, Table } from "drizzle-orm";
import * as schema from "your_schema_path";

export abstract class BaseRepository<Config extends { table: Table }> {
  constructor(
    protected db: PostgresJsDatabase<typeof schema>,
    protected readonly config: Config
  ) {}
const total = await this.db
      .select({ count: count() })
      .from(this.config.table)
      .then((res) => Number(res[0].count));
}

user.reposiotry.ts

import { BaseRepository } from "../base.repository";
import { users } from "@riskflow/db-schema";
import { eq } from "drizzle-orm";
import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
import * as schema from "your_schema_path";

export class UserRepository extends BaseRepository<{ table: typeof users }> {
  constructor(db: PostgresJsDatabase<typeof schema>) {
    super(db, { table: users });
  }

  async findByEmail(email: string) {
    return await this.db
      .select()
      .from(this.config.table)
      .where(eq(this.config.table.email, email))
      .limit(1)
      .then((res) => res[0]);
  }
}

Martial-Geek avatar Jul 28 '25 12:07 Martial-Geek

Hey everyone!

I've created this message to send in a batch to all opened issues we have, just because there are a lot of them and I want to update all of you with our current work, why issues are not responded to, and the amount of work that has been done by our team over ~8 months.

I saw a lot of issues with suggestions on how to fix something while we were not responding – so thanks everyone. Also, thanks to everyone patiently waiting for a response from us and continuing to use Drizzle!

We currently have 4 major branches with a lot of work done. Each branch was handled by different devs and teams to make sure we could make all the changes in parallel.


First branch is drizzle-kit rewrite

All of the work can be found on the alternation-engine branch. Here is a PR with the work done: https://github.com/drizzle-team/drizzle-orm/pull/4439

As you can see, it has 167k added lines of code and 67k removed, which means we've completely rewritten the drizzle-kit alternation engine, the way we handle diffs for each dialect, together with expanding our test suite from 600 tests to ~9k test units for all different types of actions you can do with kit. More importantly, we changed the migration folder structure and made commutative migrations, so you won't face complex conflicts on migrations when working in a team.

What's left here:

  • We are finishing handling defaults for Postgres, the last being geometry (yes, we fixed the srid issue here as well).
  • We are finishing commutative migrations for all dialects.
  • We are finishing up the command, so the migration flow will be as simple as drizzle-kit up for you.

Where it brings us:

  • We are getting drizzle-kit into a new good shape where we can call it [email protected]!

Timeline:

  • We need ~2 weeks to finish all of the above and send this branch to beta for testing.

Second big branch is a complex one with several HUGE updates

  • Bringing Relational Queries v2 finally live. We've done a lot of work here to actually make it faster than RQBv1 and much better from a DX point of view. But in implementing it, we had to make another big rewrite, so we completely rewrote the drizzle-orm type system, which made it much simpler and improved type performance by ~21.4x:
(types instantiations for 3300 lines production drizzle schema + 990 lines relations)

TS v5.8.3: 728.8k -> 34.1k
TS v5.9.2: 553.7k -> 25.4k

You can read more about it here.

What's left here:

Where it brings us:

  • We are getting drizzle-orm into a new good shape where we can call it [email protected]!

Breaking changes:

  • We will have them, but we will have open channels for everyone building on top of drizzle types, so we can guide you through all the changes.

Third branch is adding support for CockroachDB and MSSQL dialects

Support for them is already in the alternation-engine branch and will be available together with the drizzle-kit rewrite.

Summary

All of the work we are doing is crucial and should be done sooner rather than later. We've received a lot of feedback and worked really hard to find the best strategies and decisions for API, DX, architecture, etc., so we can confidently mark it as v1 and be sure we can improve it and remain flexible for all the features you are asking for, while becoming even better for everyone building on top of the drizzle API as well.

We didn't want to stay with some legacy decisions and solutions we had, and instead wanted to shape Drizzle in a way that will be best looking ahead to 2025–2026 trends (v1 will get proper effect support, etc.).

We believe that all of the effort we've put in will boost Drizzle and benefit everyone using it.

Thanks everyone, as we said, we are here to stay for a long time to build a great tool together!

Timelines

We are hoping to get v1 for drizzle in beta this fall and same timeline for latest. Right after that we can go through all of the issues and PRs and resond everyone. v1 for drizzle should close ~70% of all the bug tickets we have, so on beta release we will start marking them as closed!

AndriiSherman avatar Aug 30 '25 18:08 AndriiSherman

I was able to pull this off for a D1 database using RQBv2 with the following. All the type hacking is DB agnostic, so it should be adaptable to other platforms.

import { eq, type InferInsertModel, type InferSelectModel } from 'drizzle-orm';
import type { DrizzleD1Database } from 'drizzle-orm/d1';
import type { RelationalQueryBuilder } from 'drizzle-orm/sqlite-core/query-builders/query';
import type * as schema from '../schema';
import { relations } from '../schema/relations';

type TableNames = keyof typeof relations;
type TableRelations<TTable extends TableNames> = (typeof relations)[TTable];
type Querier<TTable extends TableNames> = RelationalQueryBuilder<
  'async',
  typeof relations,
  TableRelations<TTable>
>;
type TableWithRelations<TTable extends TableNames> =
  TableRelations<TTable>['table'];

export abstract class BaseStore<TTable extends TableNames> {
  constructor(
    protected readonly db: DrizzleD1Database<typeof schema, typeof relations>,
    readonly tableName: TTable,
  ) {
    this.querier = this.db.query[tableName];
    this.table = relations[tableName].table;
  }

  /**
   * The table instance for the specific table.
   * This should be used for simple queries that do not involve relations.
   */
  protected table: TableWithRelations<TTable>;

  /**
   * The querier instance for the specific table.
   * This should be used for complex SELECT queries that involve relations.
   */
  protected querier: Querier<TTable>;

  getById = async (id: string) =>
    this.db.select().from(this.table).where(eq(this.table.id, id));

  getAll = async () => this.db.select().from(this.table);

  insert = async (values: InferInsertModel<TableWithRelations<TTable>>) =>
    this.db.insert(this.table).values(values).returning().get();

  updateById = async (
    id: string,
    values: Partial<InferSelectModel<TableWithRelations<TTable>>>,
  ) => this.db.update(this.table).set(values).where(eq(this.table.id, id));

  deleteById = async (id: string) =>
    this.db.delete(this.table).where(eq(this.table.id, id));
}

One drawback is that the this.querier cannot make type inferences in the BaseStore, however classes that inherit from it can. I'm sure additional type-hacking could get it working, but this was fine for my use case.

A class that implements BaseStore looks like this:

import { BaseStore } from './BaseStore';

export class AudienceStore extends BaseStore<'audiences'> {
  getByApplicationId = async (applicationId: string) =>
    this.querier.findMany({ where: { applicationId } });
}

And the specific store implementation is created by passing the Drizzle instance and the name of the table:

    this.audiences = new AudienceStore(drizzleDb, 'audiences');

bruceharrison1984 avatar Sep 19 '25 00:09 bruceharrison1984

Is there any more ideas on this? Casting to PgTable looses all your types. The only other way I found is the cast the result, but feels a bit crap.

async find(identifier: typeof this.identifier.columnType) {
        return db
            .select()
            .from(this.table as PgTable)
            .where(
                eq(this.identifier, identifier)
            )
            .then(takeFirstOrThrow) as InferSelectModel<T>;
    }

cory-mosey avatar Oct 03 '25 11:10 cory-mosey