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

[FEATURE]: Single Table Inheritance

Open MarkusWendorf opened this issue 2 years ago • 13 comments

Describe what you want

Hello,

I would really like to see support for 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 CycleORM PHP Hibernate Java

Possible API:

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

MarkusWendorf avatar Jul 16 '23 17:07 MarkusWendorf

Thanks for the suggestion, this looks useful. We'll discuss it internally.

dankochetov avatar Jul 17 '23 00:07 dankochetov

+1 to INHERITS

PostgreSQL Docs

SebastianGarces avatar Jul 25 '23 18:07 SebastianGarces

+1 to Inherits

dcchrispen avatar Jul 25 '23 19:07 dcchrispen

Would like this feature as well

bu3alwa avatar Dec 16 '23 06:12 bu3alwa

This would be great. Like @SebastianGarces mentioned: For Postgres specifically, it would be great if we had the native table inheritance: https://www.postgresql.org/docs/current/tutorial-inheritance.html

CREATE TABLE cities (
  name       text,
  population real,
  elevation  int     -- (in ft)
);

CREATE TABLE capitals (
  state      char(2) UNIQUE NOT NULL
) INHERITS (cities);


ALTER TABLE cities
ADD test_id varchar(255); -- Both table would contains test col
DROP TABLE cities; -- Cannot drop because capitals depends on it

ALTER TABLE cities
ADD CONSTRAINT fk_test FOREIGN KEY (test_id) REFERENCES sometable (id);
  • When you add/delete/update fields -> the inheritance table will also be affected.
  • Cannot drop the parent table.
  • Foreign keys would NOT be inherited.

It could be implement via pgTable().inherits(), example:

// Parent table (cities)
export const cities = pgTable('cities', {
  name: text('name').notNull(),
  population: real('population'),
  elevation: integer('elevation'),
})

// Child table (capitals) inheriting from cities
export const capitals = pgTable('capitals', {
  state: char('state', { length: 2 }).notNull().unique(),
}).inherits(cities)

Aymericr avatar Mar 21 '24 15:03 Aymericr

+1 for inherits. Even simple single table inheritance would be super useful

slimshreydy avatar Sep 01 '24 06:09 slimshreydy

+1 to this one

curiosbasant avatar Sep 13 '24 19:09 curiosbasant

+1

t8g avatar Nov 18 '24 08:11 t8g

+1

SlavenIvanov avatar Jan 16 '25 14:01 SlavenIvanov

Want this so bad +1

vanya2h avatar Jan 29 '25 16:01 vanya2h

Came here because of this great article on the benefit of inheritance in debugging: https://www.cybertec-postgresql.com/en/debugging-postgresql-more-easily/

Just adding more fodder to motivate this one :)

scamden avatar Mar 21 '25 17:03 scamden

+1

calii23 avatar Mar 26 '25 09:03 calii23

This when? This is such a Gotcha when using drizzle for the first time :(

indrajit-roy avatar Apr 21 '25 15:04 indrajit-roy

+1

mikiyasET avatar May 21 '25 09:05 mikiyasET

We are considering using drizzle 'views' as a 'poor mans STI' and setting up discriminated unions / types ourselves. This is what Drizzle docs AI said about it:

--

For Single Table Inheritance (STI) in SQL and ORMs like Drizzle, it’s common to store all entity types in a single table, differentiating them with a type discriminator column. When subtypes have different fields, you face two main challenges: type safety at the application level and clarity when querying only relevant fields for a subtype.

Using SQL views can help address this:

  • Views for Subtypes: Define a view for each subtype that selects only the relevant columns and applies a filter (e.g., WHERE type = 'subtype'). This makes queries more ergonomic and helps ensure you only work with the fields relevant to that subtype.
  • Type Safety: In your application, you can map these views to specific types, improving type safety and reducing the risk of accessing inappropriate fields for a subtype.
  • Drizzle Support: Drizzle supports working with SQL views, so you can map these views in your schema and use them just like tables in queries.

This approach is particularly useful if you want to keep your STI implementation clean and avoid nullable columns for unrelated subtype fields. However, you should also consider your migration and maintenance workflow, since adding or changing subtype fields will require updating both the base table and the views.

In summary: using views for each subtype in STI is a practical and type-safe solution, and Drizzle’s view support makes this pattern ergonomic in TypeScript applications.

--

We will try this and see how it goes.

rchasman avatar Jul 21 '25 05:07 rchasman

+1

eastgold15 avatar Aug 30 '25 16:08 eastgold15

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