Skip to content

Support inheritance for models (Concrete Table Inheritance) #6502

Closed

Description

@felixfbecker

This needs to be supported and tested:

class Base extends Model {}
Base.init({ whatever: DataTypes.STRING }, { tableName: 'base_table' })

class Derived extends Base {}
Derived.init({ second: DataTypes.INTEGER }, { tableName: 'derived_table' })

Derived.options.__proto__ === Base.options
Derived.attributes.__proto___ === Base.attributes

Derived inherits all attributes and options from Base.

Model.init() should do something like

this.options = Object.assign(Object.create(this.options), options)

Activity

  1. added
    type: feature
    on Aug 26, 2016
  2. added this to the 4.0 milestone on Aug 26, 2016
  3. self-assigned this
    on Aug 26, 2016
  4. removed this from the 4.0 milestone on Oct 19, 2016
  5. removed their assignment
    on Oct 19, 2016
  6. yonjah commented on Jul 21, 2017

    @yonjah
    Contributor

    This looks a bit cumbersome.
    Also I'm not sure if you actually want all the options to be inherited.
    Think about this case -

    class Derived2 extends Base {}
    Derived2.init({ second: DataTypes.INTEGER }, { timestamps: false })

    If you inherit options from Base you are actually still referring the table base_table where with other models tableName would be derived from the Model.name.

    Another way to approach this is to add another static method that init will call to get options and attributes. since each Model implementation can extend this method it can have ful control on what will be inherited and what will be stayed in default. you are also not required to call init method on parents and so not locking them to specific connection and you can have more abstract models

    code example -

    class Base extends Model {
    	static getOptions (options) {
    		const defaultBaseOptions = { timestamp: false };
    		return Utils.merge(super.getOptions(defaultBaseOptions), options);
    	}
    }

    The base model will need some minor changes to the init mehtod to support this

    class Model {
    	static init(attributes, options) { // testhint options:none		
    		options = this.getOptions(options); //replacing lines 703-726
    		...
    		...
    	}
    
    	static getOptions (options) { // logic from init lines 703-726
    		if (!options || !options.sequelize) {
    			throw new Error('No Sequelize instance passed');
    		}
    		const {define: globalDefineOptions, omitNull} = this.sequelize.options;
    		const modelName = options.modelName || this.name;
    		return Utils.merge({ 
    				modelName,
    				name: {
    					plural: Utils.pluralize(modelName),
    					singular: Utils.singularize(modelName)
    				},
    				indexes: [],
    				omitNull 
    			},  _.cloneDeep(globalDefineOptions), options);
    	}
    
    }
  7. felixfbecker commented on Jul 21, 2017

    @felixfbecker
    ContributorAuthor

    Imo the examples you gave are more cumbersome, way more complex.

    tableName is not a problem because the tableName is either set explicitly or inferred from the model name. So it will always override the parent value.

    I don't understand how a method gives more control than a property. Properties are inherited just like methods, the attributes and options are already stored as properties. The options and attributes objects just need to be set to inherit from the parent's objects. It also looks weird to me to have a method getOptions that is passed options as a parameter.

  8. yonjah commented on Jul 21, 2017

    @yonjah
    Contributor

    Imo the examples you gave are more cumbersome, way more complex.

    Library code is shorter and has better seperation and user code doesn't require accessing internal properties like proto or guessing internal logic. How is it more cumbersome ?

    tableName is not a problem because the tableName is either set explicitly or inferred from the model name. So it will always override the parent value.

    Set explicitly by the options if you inherit the options which were passed to init you should inherit it as well. It is of course doesn't make since to inherit it and you can hack around it but I would try to design a consistent API with less hacks

    I don't understand how a method gives more control than a property. Properties are inherited just like methods, the attributes and options are already stored as properties. The options and attributes objects just need to be set to inherit from the parent's objects. It also looks weird to me to have a method getOptions that is passed options as a parameter.

    Properties are not inherited they are overwritten, you can not call super on an object. It might have been possible to run on the inheritance chain and merge the property but since original design decided options and attributes will be set during the init process and not when the Model class is defined it is not really an option without breaking the api.
    I agree that the init method is not really intuitive and should be deprecated but this is a major change that should have been done before v4 was released.

    I think the point about abstraction is the most important thing. if we assume users will want to set a base model with a few basic attributes like status and id and than have other models inherit from this base class like posts and users that both have status and id. it doesn't make any sense to init the base class since it is not a real model.
    I'd say this is the most common use cases and I doubt if many users will actually have base classes that should be initiated by themselves. Best case scenario you might just have useless models in your connection instance, worst case you'll have junk tables being created in your database if syncing.

    I would argue that whatever solution for inheritance you choose it must not require initializing the parent model

  9. felixfbecker commented on Jul 21, 2017

    @felixfbecker
    ContributorAuthor

    Library code is shorter and has better seperation and user code doesn't require accessing internal properties like proto or guessing internal logic. How is it more cumbersome ?

    I think you misunderstood my example. The __proto__ is only to explain the effect of the internal implemetnation. It uses ===, it doesn't change anything, it is just for explanation. Inheritance happens in the library code with the last line through Object.create().

    Set explicitly by the options if you inherit the options which were passed to init you should inherit it as well. It is of course doesn't make since to inherit it and you can hack around it but I would try to design a consistent API with less hacks

    It is inherited and then overridden. The object will have the correct value, the prototype will have the value of the parent as expected. Don't see how that's inconsistent/hacky?

    Properties are not inherited they are overwritten, you can not call super on an object. It might have been possible to run on the inheritance chain and merge the property but since original design decided options and attributes will be set during the init process and not when the Model class is defined it is not really an option without breaking the api.

    I don't understand this point, could you explain more?
    The child attributes will prototypically inherit from the parent's attributes. There is no need for super, __proto__ and Object.getPrototypeOf() will point to the parent's attributes if you need to access them (you shouldn't need to). Any later change to the parent (e.g. late setup of associations) will be reflected in the child. This is not the case if you use Utils.merge() to copy them, it would depend on the order of execution. You would be mixing inheritance semantics with mixin semantics.

    I agree that the init method is not really intuitive and should be deprecated but this is a major change that should have been done before v4 was released.

    I never said that, init is a static constructor that is crucial to implement abstractions like define() or decorators.

    I think the point about abstraction is the most important thing. if we assume users will want to set a base model with a few basic attributes like status and id and than have other models inherit from this base class like posts and users that both have status and id. it doesn't make any sense to init the base class since it is not a real model.
    I'd say this is the most common use cases and I doubt if many users will actually have base classes that should be initiated by themselves. Best case scenario you might just have useless models in your connection instance, worst case you'll have junk tables being created in your database if syncing.

    I would argue that whatever solution for inheritance you choose it must not require initializing the parent model

    One of the biggest use cases is history tables. In most serious projects you need to version and review customer data for legal reasons. There are multiple approaches to this. You could store it all in one table, but that table will not scale well with large amounts of users. Another approach is having a second table that holds history and/or change request data. Example: You have a table Users and a table UserChangeRequests. UserChangeRequests has all attributes of Users plus an attribute status that can be pending, rejected or approved. This can be modelled by having a class User and a class UserChangeRequest extends User. Both would be models in the database that share many columns. In some databases, the UserChangeRequest table can even be set to inherit columns with INHERITS FROM.

    Base classes that don't map to a table in the DB would be best modelled as an abstract class in OOP. We could add an abstract: true option to define this.
    You could also simply use a mixin, which would not pollute the inheritance chain - you could mixin these properties to any model even if they inherit from another non-abstract Model.

  10. yonjah commented on Jul 24, 2017

    @yonjah
    Contributor

    I think you misunderstood my example. The proto is only to explain the effect of the internal implemetnation. It uses ===, it doesn't change anything, it is just for explanation. Inheritance happens in the library code with the last line through Object.create().

    Sorry I missed the === thought you meant some code will need to run after the init.

    So I think our solutions are almost the same the only two main different are -

    1. Having a custom method to actually do the property extension
    2. Defining base object to extend from should not be set by calling the init method

    I think having a custom method offers better separation and allows for a cleaner code.
    For me init looks too messy and doing too much than it should. but its a minor design issue and as much as I think it will be an improvement breaking it up it's a minor issue compared to the other one.

    Let me go back to your points before explaining more the second issue -

    This is not the case if you use Utils.merge() to copy them, it would depend on the order of execution. You would be mixing inheritance semantics with mixin semantics.

    Utils.merge is used in my code because that is how Sequelize chooses to do inheritance for options, This is so options containing objects like name.plural will be able to be extended without changing name.singular. You will probably need to use it in your solution instead of Object.create if you don't want to break it

    It is inherited and then overridden. The object will have the correct value, the prototype will have the value of the parent as expected. Don't see how that's inconsistent/hacky?

    If we look at your code example any derivative of base will have the prototype - {tableName: 'base_table'}
    That means that if the derivative doesn't explicitly overwrites tableName in it's options than options.tableName === 'base_table' will always be true and will be set as the model table name -
    https://github.com/sequelize/sequelize/blob/master/lib/model.js#L767

    I never said that, init is a static constructor that is crucial to implement abstractions like define() or decorators.

    init in itself is not as bad. But we have a weird situation where a Model class actually creates Row instances instead of Models. Think about calling New Buffer(); and instead of getting a Buffer you'll get a 16bit value. So effectively Sequelize doesn't have a Model class and that is why inheritance is so messy or why your decorators doesn't really work. It is too late to fix now but it is something we should be aware of and aim to fix when possible.

    One of the biggest use cases is history tables. In most serious projects you need to version and review customer data for legal reasons.

    How many users actually use history tables ? more than having multiple tables with ids and timestamps and other properties ? More than people having multiple servers and connections they might have to attach identical models to ?

    Any way doing inheritance properly you could use them for both history tables and other solutions, but by forcing it to be part of the init process you are basically locking it to one use case.
    Also I'm not sure if history tables won't benefit more than having a built in archive property with the history table name.
    That way you can easily ask Sequelize to get data from archive and even do unions between live data and archived data.

    I think this is enough reason for wanting the inheritance process to be decoupled from the init. We should look at init as way to instantiating a Model object as if we actually had a class for it.

  11. felixfbecker commented on Jul 24, 2017

    @felixfbecker
    ContributorAuthor

    That means that if the derivative doesn't explicitly overwrites tableName in it's options than options.tableName === 'base_table' will always be true and will be set as the model table name

    All that needs to be done is default tableName to the model name. It's really not an issue. We can check options.tableName before you seting up the new object with inheritance or use hasOwnProperty().

    init in itself is not as bad. But we have a weird situation where a Model class actually creates Row instances instead of Models. Think about calling New Buffer(); and instead of getting a Buffer you'll get a 16bit value. So effectively Sequelize doesn't have a Model class and that is why inheritance is so messy or why your decorators doesn't really work. It is too late to fix now but it is something we should be aware of and aim to fix when possible.

    I think you are misunderstanding the "Model" term in Sequelize. Sequelize uses the Active Record pattern. The Model is the class, instances are concrete rows. This is not a mistake, it's a design choice. After all, classes in JavaScript are just objects themselves, so there is no reason to separate them like in v3 where there was an Instance class and a Model class. It didn't have any benefit.
    The Model class is abstract, it could just as well be named Entity or Row, it's just naming. A different name doesn't make inheritance messy or decorators not work.

    How many users actually use history tables ? more than having multiple tables with ids and timestamps and other properties ? More than people having multiple servers and connections they might have to attach identical models to ?

    The use case is huge. Any application that stores data of legal importance needs to keep a change history. Comparing the number of these users to the number of users needing "abstract" models for inheritance doesn't make sense because they don't contradict each other. With the way I suggest it, you can easily support both use cases. With your way it only supports the abstract model use case.

    Any way doing inheritance properly you could use them for both history tables and other solutions, but by forcing it to be part of the init process you are basically locking it to one use case.

    What's the problem with abstract: true?

    I think this is enough reason for wanting the inheritance process to be decoupled from the init. We should look at init as way to instantiating a Model object as if we actually had a class for it.

    I don't understand this paragraph, could you explain? init is a static constructor. It initialises the static side of the class. Models are classes and in JavaScript, classes are objects. Instantiating the concrete Model (e.g. User) is done by new User() and gives you a User instance/row.

  12. yonjah commented on Jul 25, 2017

    @yonjah
    Contributor

    I thik we are drifting to advance topics (like Liskov substitution principle and software correctness) when we are still fighting to get basic and simple inheritance working. I can't see how it has any practical effect on this discussion but I'd be happy if you could explain this idea more after we sort the basics.

    All that needs to be done is default tableName to the model name. It's really not an issue. We can check options.tableName before you seting up the new object with inheritance or use hasOwnProperty().

    And that's a hack. Simple to implement as any hack but hard to reason about.
    Why options.tableName doesn't get inherited ? any other options wont be inherited ?
    (Those are rhetorical questions the code need to reason, you don't need to answer them)

    What's the problem with abstract: true?
    Again a hack. Again more reasoning

    The use case is huge. Any application that stores data of legal importance needs to keep a change history. Comparing the number of these users to the number of users needing "abstract" models for inheritance doesn't make sense because they don't contradict each other.

    The use case might be huge it is still not bigger than having identical columns that repeat across multiple tables. Best practice say every column should have an PK field, Sequelize accommodates to easily add timestamps to every table. those are all patterns of abstract models but tightly coupled into the library implementation

    With the way I suggest it, you can easily support both use cases. With your way it only supports the abstract model use case.

    I don't know what make you think that the design I'm suggesting support both with no hacks.
    In fact history tables are much simpler to implement if we go to the abstract model since you can easily use them between different database connection (again no hacks, flags or other inconsistency compare to other Models)

    I think you are misunderstanding the "Model" term in Sequelize. Sequelize uses the Active Record pattern. The Model is the class, instances are concrete rows. This is not a mistake, it's a design choice.

    This is a valid point. I guess we should have asked our self if this copying rails design one to one is so important or if there might be a reason why that API was never identical in Sequelize and if following JS coding style doesn't make more sense where we are now .
    But you are correct that the idea not to have Model classes and only to have row classes was an aware decision to try and copy ActiveRecord API. I never really liked rails, and I wonder how this was done with rails ? I would imagine there native classes has a bit more features than JS to support this decision.

    I don't understand this paragraph, could you explain? init is a static constructor. It initialises the static side of the class.

    I'll try to be a bit more clear on this cause this is the main issue.
    You don't initialize Classes you initialize Objects (yea I know everything in JS is an Object but that doesn't mean we have to abuse the language).

    Now init has two major roles -

    • It finalizes the class definition with dynamic properties
    • It attaches the class to a connection

    This is wrong not only because we want each function to have a specific role but because we want our classes to be defined once when it's created and not to be open for changes after it was already defined (There is a reason why those methods and properties are refereed to as Static in OOP and many other languages don't let you just replace them)

    Since Static methods are inherited when we extend a Class this inheritance will just work out of the box without any issues.

    But we have two problems with implementing this -

    1. JS doesn't support static properties on a class.
    2. Even if it did properties would just override each other, but since we need to merge complex object that's not good enough for this use case.

    Since JS is quite flexible we can try and hack the first issue out (we shouldn't) but we can't really solve the second one (unless we move away from the ActiveRecord design). So the less hacky solution that is natively supported is to have a static method that its role is to create those semi dynamic attributes when they are needed.
    To still make sure we only inherit static values those values should be statically defined with the instance and not changed.

    The other great benefit of this solution is that we can still get it to work with our current design (Where attributes are set when calling init and not when defining the Class without any breaking changes.
    I must say I'm not sure how this will work with the decorators, but I would imagine that if the decorator function is called on the prototype when the class is created it would probably be possible to hook into this logic and make them work as well

    Yes we can use the init method for this but this one already has too many roles and it should be separated (We don't want to extend the init method just to add another attribute)

  13. yonjah commented on Jul 25, 2017

    @yonjah
    Contributor

    @felixfbecker I just noticed you already had the exact discussion with almost the same ideas and comments in #6524. I really wished I could be refereed there since it would have saved both of us a lot of time, but I guess with so much active communication going on in this project it is easy to forget which discussion you already had and when.

    Any way I think the issues I raised are explained very clearly there and I don't think I have much to contribute and it seem like you made your mind about this (Even though I share the dream of having a Models that are decoupled from the connection and I don't think it is something that's very hard to achieve ( it's not easy but it is probably doable ))

    Any way I'm going to stop wasting my time now

  14. schieck0 commented on Jun 9, 2021

    @schieck0
  15. tommaroney commented on Jan 12, 2023

    @tommaroney

    @schieck0 isn't the only engineer frustrated with the lack of responsiveness here. Inheritance is a basic feature of OOP. It's disappointing it hasn't been made a priority by the Sequelize team.

  16. ephys commented on Jan 13, 2023

    @ephys
    Member

    We're actually working on this as part of our new model definition implementation. Mostly tracked here: #15334

  17. moved this to Before v7 in Roadmapon Mar 12, 2023
  18. mschipperheyn commented on Apr 24, 2023

    @mschipperheyn

    It might be an idea to have a look at all the use cases Hibernate deals with in this respect. It might help avoid some reinvention of the wheel. Even years ago it had a level of sophistication that even today Javascript OOMs don't come close to (although the typescript / decorator combo brings it a lot closer).

    I remember it supported various strategies for dealing with inheritance, which you had to choose explicitly, e.g. using a discriminator column in a single table strategy, table per class or using sub tables for diverging properties.

    There were also obvious performance and storage trade offs. E.g. if I recall using sub tables could lead to large LEFT JOIN statements which impacted performance. Imagine using a nested include with an inherited class that is set up this way.

    And of course, you would also want to be able to "just" query for a subclass and not get the siblings. It seems like a feature that has a lot of trickyness to it.

    I personally don't understand why the roadmap associates it with v7 instead of v8. v7 already has the spectacular typescript improvements. Why push the timeline with this nice to have? Leave some spectacle for v8!

    https://www.baeldung.com/hibernate-inheritance
    https://thorben-janssen.com/complete-guide-inheritance-strategies-jpa-hibernate/

  19. ephys commented on Apr 24, 2023

    @ephys
    Member

    We're including it in v7 because we're merging with sequelize-typescript and sequelize-typescript includes support for inheritance. However we're only implementing the "one table per class" (concrete table inheritance) inheritance type (in v7) which is the easiest one to implement (all the necessary building blocs are there, need to glue them together) and will only work with decorators

  20. ephys commented on Jun 17, 2023

    @ephys
    Member

    Support for the style of model inheritance I mentioned above has been merged #16095. This is what this issue was initially about so I'm going to close it as completed.

    If support for other styles of inheritance is desired, please don't hesitate to open a new issue. One already exists for Joined Table Inheritance: #1243

  21. moved this from Before v7 to Done in Roadmapon Jun 17, 2023
  22. changed the title [-]Support inheritance for models[/-] [+]Support inheritance for models (Concrete Table Inheritance)[/+] on Jun 26, 2023
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

    type: feature

    Type

    No type

    Projects

    • Status
      Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions