drizzle-team / drizzle-team/drizzle-orm

[FEATURE]: Single Table Inheritance

Open
#900 17 comments 29 reactions 0 assignees View on GitHub
db/postgres drizzle/kit enhancement
Dominant language
TypeScript
Stars
35.8k
Forks
1.6k
Avg merge
2d 7h
Merged PRs (30d)
4

Description

### Describe what you want

Hello,

I would really like to see support for [single table inheritance](https://en.wikipedia.org/wiki/Single_Table_Inheritance) in drizzle.

Single table inheritance is a way to save inheritance structures to a single database table. Imagine a `accommodation` class in OOP, which can be either a `hotel` or a `motel`. Both sub-classes inherit a set of properties from the parent (only `id` in this case) but each class also has additional fields (`hotelName` or `motelName`) that are unique to their specific class.

You could save it in the database like this:

| type | id | hotelName | motelName
| ------------- |:-------------:| -----:|-----:|
| hotel | 1 | Hotel-Name-1 | NULL
| motel | 2 | NULL | Motel1
| hotel | 3 | Hotel-Name-2 | NULL

Prior work in other ORMs:
[TypeORM Node.js](https://orkhan.gitbook.io/typeorm/docs/entity-inheritance#single-table-inheritance)
[CycleORM PHP](https://cycle-orm.dev/docs/advanced-single-table-inheritance/current)
[Hibernate Java](https://www.baeldung.com/hibernate-inheritance#single-table)

Possible API:

```typescript
pgTable({
id: serial("id"),
type: text("type"),
})
.addChildEntity({
type: 'hotel',
hotelName: text("hotelName"),
})
.addChildEntity({
type: 'motel',
motelName: text("motelName"),
});
```

The output type should be a discriminated union for: `type Table = Hotel | Motel` based on the value of `type`.
Not sure how well this API works out in practice (type inference, relations?).

Thanks

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.