Skip to content

Support InheritsFrom association (Joined Table Inheritance) #1243

Description

@ludydoo

I am using sequelize but ran into the problem of it not supporting model inheritance.

I would suggest implementing an InheritsFrom association, that would be basically the same as the BelongsTo association. Though, when persisting a new object, sequelize would chain-create all subclass objects and persist them first. It would also allow an object to share the getters/setters of its superclass instances.

  module.exports = (function() {
  var InheritsFrom = function(source, target, options) {
    this.associationType      = 'InheritsFrom'
    this.source               = source
    this.target               = target
    this.options              = options
    this.isSingleAssociation  = true
    this.isSelfAssociation    = false
    this.as                   = this.options.as

I figured I could add the InheritsFrom and Superclasses options to the dao-factory.js,
Also, I would add InheritsFromInstance and SuperClassInstance in the dao.js

  var DAOFactory = function(name, attributes, options) {
    this.options = Utils._.extend({
      timestamps: true,
      ...
      inheritsFrom : null
      superClasses : {}
    }, options || {})

Calling the dao get from a inherited dao would look for the key, and if it was not found, look for the key in the sub dao, until it finds the correct getter. Also, if a getter/setter was called from a superclass dao, it would find the last inherited dao, and start to find the key from there.

DAO.prototype.get = function (key) {
    if (key) {
      if (this._customGetters[key]) {
        return this._customGetters[key].call(this, key)
      }
      return this.dataValues[key]
    }

    if (this._hasCustomGetters) {
      var values = {}
        , key

      for (key in this._customGetters) {
        if (this._customGetters.hasOwnProperty(key)) {
          values[key] = this.get(key)
        }
      }

      for (key in this.dataValues) {
        if (!values.hasOwnProperty(key) && this.dataValues.hasOwnProperty(key)) {
          values[key] = this.dataValues[key]
        }
      }
      return values
    }

    //Here, check if the superclass has the get methods

    return this.dataValues
  }

I think I have to add some _customGetters and _customSetters in the dao-factory.js, but could somebody help me out and point me where in the codebase should I add such functionality? There is very few comments in there!

Please comment !

Activity

  1. saschagehlich commented on Jan 13, 2014

    @saschagehlich
    Contributor

    I like the idea! 👍

  2. mickhansen commented on Jan 13, 2014

    @mickhansen
    Contributor

    I like the idea, but i need some clarification.

    If i understand it correctly, you want to be able to extend, not just the model, but the data it holds in a seperate table, right?

    So if B.inheritsFrom(A) - It doesn't just extend attributes, class and instance methods and create a seperate entity - B will actually use A's dataset/table?

    That would be extremely complex to develop, although very interesting.

  3. ludydoo commented on Jan 13, 2014

    @ludydoo
    Author

    It "should" be the same entity, but I think it would be easier for it not to be.

    I looked for a ORM that does this already, but found none in no language. ActiveRecords only support single table inheritance, dumping all the fields in a single table.

    There is three types of "inheritance mappings"

    • Single table per class, where all the fields are concatenated into a single table, containing all properties of every possible subclass
    • Concrete table inheritance, where there are only tables existing for "concrete" classes, or "leaf" classes
    • One class per table, (this I am suggesting), where there is one table for each class

    For this enhancement :

    I think the models should be separate entities. It should only navigate through the inheritance tree up and downstream, each node being a distinct sequelize entity, through the inheritsFrom and isSuperClassedBy properties. I'm not sure what would happen if a method or a field was redefined. I would rather "simulate" inheritance by adding the isSuperclassedBy and classInheritsFrom properties, instead of extending the model (ala Backbone). For sure it would be prettier, but... anyways.

    Let's dive into an example :

    B.inheritsFrom(A)
    B.name
    A.age

    If I call B.getName(), i should receive A.getName()

    When it becomes interesting :

    C.inheritsFrom(B).inheritsFrom(A) and D.inheritsFrom(B).inheritsFrom(A)

    • C.Pet
    • D.Bird
    • B.Name
    • A.Age

    The main problem in this structure is : navigating up and downstream. It poses two problems in sequelize :

    First, A doesn't have any information about what type of leaf class it really superClasses. I suggest adding Class.type whenever a class superclasses at least two classes, for easily navigating upstream (instead of having to iterate through each possible children classes and find its own id in the foreign key). In the case of a C object being instantiated, B.Type = C. (B superclasses C and D, so it needs to know which type it is, and A only superClasses one Class, B, so it already knows where to look for its superclasses instances). I would also add A.leafClass so that A already knows what type of leaf it has.

    Second problem, getters and setters. They should be asynchronous! If I want to access a property of a super instance, I need first to get that instance (which is asynchronous, unless it is eagerly loaed).

    Let say C.getAge() // a normal getter, in all its glory! But! C.age doesn't exist! In reality, we want A.age !

      1. Check if C.age is in the C.dataValues keys / customGetters C.getAge()
      1. Check if C is superclassed by some class
    • 2.1 It is!!! call getParentClassInstance() // Should return instance of B (asynchronous / eagerly loaded)?
    • 2.2 check if B.age is in B.dataValues or customGetter B.getAge()
    • 2.3 check if B has parent class instance
    • 2.4 if so, call getParentClassInstance() // Should return instance of A, again, (asynchronous / or eagerly loaded)?.
    • 2.5 check if instance of A has A.age in dataValues keys. Found. return that value
  4. ludydoo commented on Jan 13, 2014

    @ludydoo
    Author

    Oh and for creating a C object, you only need to attach BeforeCreate hooks to the parents classes so it does :

    C. BeforeCreate
    B.BeforeCreate
    A.BeforeCreate
    A.Create
    B.Create (with A_id = A.id)
    C.Create (with B_id = B.id)

  5. ludydoo commented on Jan 13, 2014

    @ludydoo
    Author

    For eagerly loaded inheritance instances :

    SELECT 
    
    // C table
    C.id as C_id,
    C.Pet as C_Pet,
    C.B_id as C_B_id
    
    // B table
    B.id as B_id, //C_B_id and B_id are the same
    B.name as B_name,
    B.A_id as B_A_id 
    
    // A table
    A.id as A_id //B_A_id and A_id are the same
    A.age as A_age
    
    from C
    inner join B
    on B.id = C.B_id
    inner join A
    on A.id = B.A_id
    
    where //...
    
  6. mickhansen commented on Jan 13, 2014

    @mickhansen
    Contributor

    Would be way easier for it to be the same entity. I.e. extends just means a model with attributes, instance/class methods, associations inherited. And then work like it's own model.

  7. ludydoo commented on Jan 13, 2014

    @ludydoo
    Author

    You're surely right, I haven't analyzed the codebase thoroughly. What about the async/eagerly loaded getters and setters?

  8. mickhansen commented on Jan 13, 2014

    @mickhansen
    Contributor

    async getters and setters pose a big issue in then having to wait for async setters in save() etc.
    Honestly i don't see feel like this should make it into core, it will add a lot of complexity, this would be ideal as a plugin - But need to hear from the others.

    Thoughts @sdepold, @durango, @janmeier?

  9. mickhansen commented on Jan 13, 2014

    @mickhansen
    Contributor

    What i mean is doing this kind of virtual table inheritance where B can get data from (and set) table A etc, would be very complex.

  10. mickhansen commented on Jan 13, 2014

    @mickhansen
    Contributor

    But would definitely be willing to discuss this further, it would need a serious spec first atleast.

  11. ludydoo commented on Jan 13, 2014

    @ludydoo
    Author

    What parts of the code do you think this enhancement would affect most?

  12. mickhansen commented on Jan 13, 2014

    @mickhansen
    Contributor

    Hmm, i suppose it would primarily be the setting and getting of values and associations.
    But the async setting of values has an impact on updateAttributes and save() at the least. And it means we have to support both sync and async cases.

  13. ludydoo commented on Jan 13, 2014

    @ludydoo
    Author

    For async getters and setters : #965

  14. ludydoo commented on Jan 13, 2014

    @ludydoo
    Author

    A thought about this :
    If sequelize created Views for these inherited concrete leaf classes, containing all the info from the base classes, the getters would not have to be async. For setters, since inserting in a view is handled differently in different db engines, INSTEAD triggers could be written.

    Edit : In fact, stocked procedures would be easier than views for both update, insert, delete and find operations.

  15. ludydoo commented on Jan 14, 2014

    @ludydoo
    Author

    I've forked the repo and started working on a possible workaround, with no need for async getters / setters.
    https://github.com/ludydoo/sequelize/commit/327086f8a1265cac16b43503fd50b2d342036c32

    Would love to hear comments about that !

  16. 100 remaining items

  17. abelosorio commented on Jan 17, 2020

    @abelosorio

    This is still an issue. A big one!

  18. added
    hard to reproduce
    status: understood
    hard
    and removed
    hard to reproduce
    on Jan 19, 2020
  19. ahmadzahabi1 commented on Apr 17, 2020

    @ahmadzahabi1

    I recommend to implement this feature in the future.

  20. LarissaGuder commented on Jun 9, 2021

    @LarissaGuder

    Almost seven years.
    Any predictions to be implemented, or is not in scope for now?

  21. deleted a comment from schieck0 on Dec 9, 2021
  22. removed
    status: understood
    on Nov 7, 2022
  23. changed the title [-]Support InheritsFrom association[/-] [+]Support InheritsFrom association (Joined Table Inheritance)[/+] on Jun 26, 2023
  24. added theissue type on Mar 9, 2025
  25. removed
    type: feature
    on Mar 9, 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

    hard

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions