Skip to content

RFC: Add support for inheritance in model files #1873

Closed
1 of 1 issue completed
Closed

Description

@vlidholt

A common feature request for Serverpod is to add support for inheritance in model files. It's easy to see how this can be a handy feature. The current approach is to support similar functionality through composition. But there are obvious pros of using inheritance instead.

inheritance

  • By using inheritance over composition, it would be possible to guarantee that fields are present instead of having nullable fields to compose different types of similar objects.
  • We could support sealed classes. This would be great to ensure that developers handle all possible cases for a message with different compositions.

However, adding classes is a challenging task.

  • To seal the classes, we will need to either place them in the same file or use the part of directive.
  • Deserialization of inherited classes is tricky because we do not necessarily know the type of the class we are deserializing.
  • How do we handle database tables?

Implementation

Several aspects need to be considered to implement inheritance in model files.

  • Add an (optional) extends and sealed keyword to the model files. The keyword. A base class can set sealed to true, in which case the class also becomes abstract. Any model in the package that extends the sealed class will be part of the seal.
  • All generated files need to be connected through part of to support the seal feature.
  • When serializing classes that use the extends keyword, the serializer will also save the class name (in the same way this happens in streams or when caching objects).
  • In the first version, we can make tables optional for extended models, but it should be possible to add a table name to the extended model and just add all columns in the object-relation mapping.

Examples

Setting up a sealed model:

class: MyModel
sealed: true
fields:
  name: String

Extending a model:

class: MyExtendedModel
extends: MyModel
fields:
  anotherName: String

(Maybe) not in the first version, add a table to an extended model:

class: MyExtendedModelWithTable
extends: MyModel
table: my_extended_model_with_table
fields:
  yetAnotherName: String

Previous discussions on the topic:
#1618
#793

Sub-issues

Sub-issues

1 of 1 Issues completed
Loading 1 sub-issues

Activity

  1. moved this to Version 2.0 - Nice to have 🥳 in Serverpod Frameworkson Feb 6, 2024
  2. lukehutch commented on Feb 22, 2024

    @lukehutch
    Contributor

    In the first version, we can make tables optional for extended models, but it should be possible to add a table name to the extended model and just add all columns in the object-relation mapping.

    +1 on this -- I can envision cases where a subclassed model should be able to be used to write to a parent model's table (where any fields added in the subclass are dropped, i.e. they become client/server-only fields, but are never persisted to the database), but also cases where a subclassed model should be able to be associated with its own table (whether or not it adds its own fields).

  3. dkbast commented on Mar 11, 2024

    @dkbast
    Contributor

    Having sealed classes would be super handy - currently migrating a small project to serverpod to see how it fits into my tech stack and since I was using sealed classes I landed here. For now I will go ahead with reusing my freezed class as a custom model which may be "good enough" for now :)

    UPDATE: it appears to be impossible to mix freezed classes and those generated by Serverpod due to different fromJson signatures and json_serializable not being ok with that. (Can't even nest freezed classes when specifying the serverpod serializer) This a bit of a bummer and makes complex custom models way too hard to use. I decided to simply my data structure to make it conform with the generator, but having a different option would be great :)

    Just saw this RFC again, and from what I remember "Hibernate" from the Java world did a pretty good job at this - https://www.baeldung.com/hibernate-inheritance for a good overview

  4. added
    rfc
    enhancement
    on Jul 12, 2024
  5. BenAuerDev commented on Aug 13, 2024

    @BenAuerDev
    Contributor

    I'll pick this one up :)

  6. moved this from Later 🥳 to Now 🔥 in Serverpod Frameworkson Aug 13, 2024
  7. lukehutch commented on Aug 13, 2024

    @lukehutch
    Contributor

    @BenAuerDev see also #1618... This issue is a dup of that. Note especially the last comment, tangentially related to inheritance (since a subclass model object should be able to be written into a superclass model's table): it would be nice if there was support for writing the same model into multiple tables, so that backups can be maintained (eg for law enforcement data retention purposes).

  8. BenAuerDev commented on Aug 14, 2024

    @BenAuerDev
    Contributor

    Thanks @lukehutch I'll look into it 🚀 🚀

  9. SandPod commented on Aug 29, 2024

    @SandPod
    Contributor

    Related issue closed as a duplicate: #793

  10. gazialankus commented on Nov 29, 2024

    @gazialankus

    Thank you for implementing inheritance.

    Is there any way to extend classes from other modules?

    class: User
    extends: UserInfo # module:auth:UserInfo or auth:UserInfo don't work either
    
    serverpod generate --experimental-features=all
    Enabling experimental feature: all.
    ⠙ Generating code... (1ms)
    
    Found 1 issue.
    Error on line 2, column 10 of lib\src\models\user.spy.yaml: You can only extend classes from your own project.
      ╷
    2 │ extends: UserInfo
      │          ^^^^^^^^
      ╵
    

    It identifies UserInfo correctly here, writing UserInfoo gives another error.

    Is there a way to extend UserInfo?

    cc @BenAuerDev

  11. BenAuerDev commented on Nov 29, 2024

    @BenAuerDev
    Contributor

    Hi @gazialankus!
    Thanks for trying out the inheritance feature 🚀
    Unfortunately, this is not possible. To support subclassing, parent classes are structured differently from standard classes. To avoid modifications to classes critical to the framework's functionality, we’ve put this restriction in place.

  12. added
    area: models
    on Dec 19, 2024
  13. moved this from Next 🌟 to Later 🥳 in Serverpod Frameworkson Jan 22, 2025
  14. connordodge commented on Jan 22, 2025

    @connordodge

    I'm working on a project right now where I'm exploring serverpod, and I want to use inheritance, mixins, and/or interfaces for my serverpod classes. Trying to figure out how to do that led me to this issue, and I'm glad to see it getting worked on. It looks like some progress was made, but I'm seeing that this was moved from Next to Later in the roadmap just a few hours ago. Is there a release coming up and this just isn't ready, or has this been put on hold for now?

    EDIT - Nevermind, I see that there is no assignee to work on it. Thanks!

  15. SandPod commented on Jan 22, 2025

    @SandPod
    Contributor

    @connordodge - Glad to hear you are exploring Serverpod!

    I did some cleanup in our roadmap to better clarify what is being worked on right now and what is next up. There is still quite a lot of work left before the inheritance is stable but we intend to finish that work during this spring.

    A separate initiative will be interface support: #2842

  16. connordodge commented on Jan 22, 2025

    @connordodge

    Glad to hear it! Thank you.

  17. SandPod commented on Jun 24, 2025

    @SandPod
    Contributor

    Update: There are limitations in our protocol layer that prevent us from finalizing inheritance. The experimental feature can be used as is, but information is lost when serializing classes that utalize inheritance.

    This is outlined in the documentation and we need a good way to solve this issue before inheritance can be stabilized: https://docs.serverpod.dev/concepts/experimental#inheritance

  18. moved this from Later 🥳 to Backlog 🗂️ in Serverpod Frameworkson Jun 24, 2025
  19. gazialankus commented on Aug 28, 2025

    @gazialankus

    The current state for database models and inheritance:

    • You can have only one model be a database model in a hierarchy chain. In an inheritance scenario of one parent with two children, either the parent or the children can be a database model, but not both.
    • So in the example of animal being parent of cat and dog, you can have tables for cat and dog separately and have them inherit from the non-database class animal.
    • Therefore you cannot have this in your database: an animal_owner table that has a relation with animal. What you can have is cat_owner and dog_owner that has relations with cat and dog.
    • So it's limited if you're eyeing inheritance and thinking of using it to create generic relations in your database.

    Just wanted to share this as a tip for others that may be considering inheritance and and database support for it. Initially I didn't understand #2799 well enough but after doing a trial and error it all made sense.

  20. TheLastGimbus commented on Sep 13, 2025

    @TheLastGimbus

    Hi 👋 I wanted to share what I'm doing to give some perspective:

    I'm making a kayaking gear rental app. All gear has it's producer and name, and I want to put their all id's as foreign key in rentals table. But:

    • kayaks have their weight-ranges
    • paddles have lengths
    • vests have sizes, etc

    So, classic inheritance, right?

    So I followed this very elegant pattern: https://stackoverflow.com/a/3579462 and just made separate table for extra type-specific data

    # gear.spy.yaml
    class: Gear
    table: gear
    fields:
      type: GearType
      manufacturer: String?
      model: String?
      friendlyName: String?
      photoUrls: List<Uri>?
    
    # gear_kayak.spy.yaml
    class: GearKayak
    table: gear_kayaks
    fields:
      gear: Gear?, relation(onUpdate=NoAction, onDelete=Cascade)
      minWeight: int?
      maxWeight: int?
    indexes:
      kayaks_gear_unique_idx:
        fields: gearId
        unique: true
    
    # gear_paddle.spy.yaml
    class: GearPaddle
    table: gear_paddles
    fields:
      gear: Gear?, relation(onUpdate=NoAction, onDelete=Cascade)
      type: PaddleType
      length: double
    indexes:
      paddles_gear_unique_idx:
        fields: gearId
        unique: true

    And now, every function/widgets that deals with them looks like

    Widget gearInfo(Gear gear, dynamic extra) {
      Text(gear.name),
      switch(extra) {
        GearKayak kayak => Text(kayak.weight),
        GearPaddle paddle => Text(paddle.length),
        _ => Text('wtf'),
      }
    }

    Or, i could even skip the first gear parameter, (since subtypes include it from join query) and blindly type extra.gear.name

    Well, i didn't sign up for high-oop statically typed language to use dynamic everywhere 😒😒


    So, I would ❤️love❤️ if I could have a dummy GearExtra sealed class that would include all of them, and then could do

    Widget gearInfo(Gear gear, GearExtra extra) // <- must be one of them

    BUT this is currently impossible if child-classes are also database tables 😔😔 - i don't know why - probably because that could imply that they should also have some common behavior with the db - like GearExtra.db.findAll() - but that's not really needed (at least for me 😛) - i just need my Dart to behave

    OR, in some distant universe, if we could have all of this oop-inheritance working with db full scale - that is, i could just make my sealed Gear class, then extend it in all gear subtypes, and serverpod's generator would do all of extra-table stuff automatically - I know this is a bit over-the-moon, I'm very happy with my GearExtra for now 🙏🙏

  21. SandPod commented on Sep 19, 2025

    @SandPod
    Contributor

    @TheLastGimbus Is GearExtra still restricted if it is not a table class but simply a sealed class without a table? I believe we should allow this if I remember the implementation correctly.

  22. TheLastGimbus commented on Sep 24, 2025

    @TheLastGimbus

    @SandPod oh yesss, little update - i did manage to make GearExtra a sealed class and other make other subtypes extends it - but, it turns out that the top-level GearExtra doesn't even generate fromJson - as said by @obiwanzenobi in #3173 (comment)

    So it's semi-useless, because i cannot use it in endpoints - i think that only part that's common inside GearExtra is sent (no subtype data) - and since in my case there is nothing, i still need to

    Future<List<(Gear, GearBelt)>> getAllBelts(Session session) { ... }
    Stream<List<(Gear, GearBelt)>> watchAllBelts(Session session) { ... }
    Future<List<(Gear, GearClothing)>> getAllClothes(Session session) { ... }
    Stream<List<(Gear, GearClothing)>> watchAllClothes(Session session) { ... }
    Future<List<(Gear, GearFloatbag)>> getAllFloatbags(Session session) { ... }
    Stream<List<(Gear, GearFloatbag)>> watchAllFloatbags(Session session) { ... }

    and then on the client

    Future<List<GearPair>> getAllGear() async {
      final allLists = await Future.wait([
        _client.gearRead.getAllBelts(),
        _client.gearRead.getAllClothes(),
        _client.gearRead.getAllFloatbags(),
        ...
    
      ]);
      return [
        for (final list in allLists) ...list,
      ].map((e) => GearPair(gear: e.$1, gearExtra: e.$2)).toList(growable: false);
    }
  23. marcelomendoncasoares commented on Nov 17, 2025

    @marcelomendoncasoares
    Collaborator

    With the merge of #4227, polymorphism is now officially supported in endpoints and will be available on Serverpod 3.0! Since this is the last missing piece holding the feature as experimental, we will also consider this RFC closed and deal with the evolution of the feature as natural enhancement.

    @TheLastGimbus The lack of fromJson on sealed classes should no longer be an issue, since now we deserialize all classes using the Protocol().deserialize method - that will forward the deserialization to the child class, ignoring the presence or absence of fromJson on the base class. If you can try your use case with the latest main, it would be great to have your feedback on the feature!

  24. moved this from Backlog 🗂️ to Done 🚀 in Serverpod Frameworkson Nov 17, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: modelsenhancementrfc

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions