Skip to content

[BUG]: Field name overwrites join with null [Relationship builder] #640

Open
@TheDevMinerTV

Description

@TheDevMinerTV

What version of drizzle-orm are you using?

0.26.1

What version of drizzle-kit are you using?

0.18.1

Describe the Bug

  1. Have a field inside a table with the same DB-native name as another object
export const users = sqliteTable('users', {
  id: text('id').primaryKey(),
});

export const usersRelations = relations(users, ({ many }) => ({
  tokens: many(tokens),
}));

export const tokens = sqliteTable('tokens', {
  id: integer('id').primaryKey(),
  userId: text('user').notNull(),
  //            ^^^^
  // Notice the field name here
  // This is duplicate with the name below
});

export const tokensRelations = relations(tokens, ({ one }) => ({
  user: one(users, {
// ^^^
// This duplicates the field above
    fields: [tokens.userId],
    references: [users.id],
  }),
}));
  1. Query the Token with the relational query builder:
const dbUser = await request.db.query.tokens.findFirst({
  where: eq(tokens.id, 1),
  with: {
    user: {
//  ^^^^
//  This here is the issue, I assume Drizzle doesn't know which one to
//  query
      columns: {
        id: true,
      },
    },
  },
});

The types for dbUser is the following:

const dbUser: {
    id: number;
    userId: string;
    user: {
        id: string;
        tokenType: string;
        accessToken: string;
    };
} | undefined

but at runtime the type is this:

{
  id: 1,
  userId: '81095245',
  user: null
}

I'm not quite sure why user here is null but renaming the first field in the DB fixed it.

Expected behavior

The object should not contain null at runtime.

Environment & setup

Cloudflare Workers + Cloudflare D1 (SQLite)

Notes

If anyone finds a better title, please suggest / edit it :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions