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
23.54k stars 578 forks source link

[BUG]: Typing issue when using tables with the same name across different schemas #2387

Open stLmpp opened 4 months ago

stLmpp commented 4 months ago

What version of drizzle-orm are you using?

0.30.10

What version of drizzle-kit are you using?

0.21.4

Describe the Bug

query.findMany/findFirst does not show relations on "with" property and the result query when declaring 2 (or more) tables with the same name across different schemas.

Example:

// schema.ts

import { integer, pgSchema, serial } from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';

export const schema1 = pgSchema('sch1');
export const schema2 = pgSchema('sch2');

export const sch1Table = schema1.table('table', {
  sch1Id: serial('sch1_id').primaryKey(),
  sch2Id: integer('sch2_id')
    .references(() => sch2Table.sch2Id)
    .notNull(),
});

export const sch1Relations = relations(sch1Table, ({ one }) => ({
  sch2Table: one(sch2Table, {
    references: [sch2Table.sch2Id],
    fields: [sch1Table.sch2Id],
  }),
}));

export const sch2Table = schema2.table('table', {
  sch2Id: serial('sch2_id').primaryKey(),
});

export const sch2Relations = relations(sch2Table, ({ many }) => ({
  sch1Table: many(sch1Table),
}));

When trying to query this two tables, this happens in the IDE:

image

However, this is only a type error, since the result of the queries returns correctly:

image

One workaround that I found is to cast the name as anything else:

export const sch1Table = schema1.table('table' as 'table1', {
  sch1Id: serial('sch1_id').primaryKey(),
  sch2Id: integer('sch2_id')
    .references(() => sch2Table.sch2Id)
    .notNull(),
});

Expected behavior

It should autocomplete the relations inside "with" and show the correct return type

Environment & setup

Reproduction: https://github.com/stLmpp/drizzle-orm-issue-same-table-name-different-schema

I'm using Webstorm, but the same thing happen in Vscode.