Skip to content

Make Instances instances of Model - #5877

Closed
felixfbecker wants to merge 0 commit into
sequelize:masterfrom
felixfbecker:master
Closed

felixfbecker wants to merge 0 commit into
sequelize:masterfrom
felixfbecker:master

Conversation

@felixfbecker

@felixfbecker felixfbecker commented May 12, 2016 •

Copy link
Copy Markdown
Contributor

This PR does some changes I suggested in #5205 (comment) and #4728 (comment). I could not get the tests to run so I open this to see what CI says and to generate some discussion.

  • This removes the Instance class, it essentially becomes the Model class.
  • All the prototype methods of the old Model class (find(), build(), ...) are now static methods on the new Model class.
  • The code of the old constructor of the Model class is added to the static initializer Model.init().
  • sequelize.define() is basically now a class factory, that returns a new class that inherits from Model, initialized with the passed options.
  • User.build() instanceof User is now true.
  • Instead of passing instanceMethods, classMethods getterMethods, setterMethods you can now simply set those methods on the Model / the Model's prototype directly which is awesome for strict typing (TypeScript)
  • Instead of using Model.build() you can also just use new Model() to get an instance
  • To check if a variable is a Model, you have to check x.prototype instanceof Model, to check if a variable is an instance of a Model you have to check x instanceof Model
  • The property instance.Model is now exactly the same as instance.constructor (a reference to the class that created the object)
  • For BC the references .Instance are still there and set to the Model class (since the Model class replaces the Instance class)
  • Model.name is set to the model name in sequelize.define() via Object.defineProperty. Only in the super-old Node versions, where Function.prototype.name is not configurable, eval() is used to dynamically create a class with the model name.

Changes in semantic, expressed in TypeScript definitions:

abstract class Model {
  static init(attributes: ModelAttributes, options: ModelOptions, modelManager: ModelManager): void;
  static find(options: FindOptions): Promise<Model>;
  save(options?: InstanceSaveOptions): Promise<void>;
}

class Connection {
  define(modelName: string, attributes: ModelAttributes, options?: ModelOptions): typeof Model;
}

Model creation with define() as a class factory is supported just like before, but it is in theory also possible to subclass Model directly for type-safety and call Model.init() yourself:

class User extends Sequelize.Model {
  public username: string;
  myMethod() {
    return 'hello';
  }
}
Model.init(User.name, {username: Sequelize.STRING}, {tableName: 'users'}, sequelize.modelManager)

Model.init() is of course low-level API that is called by define(), but it would finally allow third-party wrappers to do this in decorators: A model would extend Sequelize.Model (similar to how it is today), property/method decorators would add metadata about types, hooks, associations and a class decorator would read them and call the static initializer Model.init() with the info.

@overlookmotel

Copy link
Copy Markdown
Contributor

Hmm interesting. new User() rather than User.build() is really nice.

However, under this new scheme, is there a way to add a method universally to all instances of all models? At present you can do Sequelize.Instance.prototype.myMethod = function() { /* blah */ } and that works even after models have been defined.

How would you do that under the new scheme? Being able to add (or shim) methods on the universal Model Instance prototype is very useful for plugins.

Also...

To check if a variable is a Model, you have to check x.prototype instanceof Model, to check if a variable is an instance of a Model you have to check x instanceof Model

x.prototype instanceof Model doesn't seem ideal to me. But I'm not sure what else could be done.

@overlookmotel

overlookmotel commented May 13, 2016 •

Copy link
Copy Markdown
Contributor

It's tricky. Depending on the circumstances, you want user instanceof User but also User instanceof Model. It's not possible to have both.

Which should take precedence is probably a matter of opinion. Which feels "right" will be different for different users depending on what they use Sequelize for.

As someone who maintains a few Sequelize plugins, I see the schema more in the abstract so the power that User instanceof Model gives is more important for me, but for a more straightforward Sequelize consumer, all they probably care about is user instanceof User.

@overlookmotel

Copy link
Copy Markdown
Contributor

By the way, would x instanceof Sequelize.Model tell you whether x is a model instance (which model unspecified)?

@felixfbecker

Copy link
Copy Markdown
Contributor Author

@overlookmotel

However, under this new scheme, is there a way to add a method universally to all instances of all models?

Sure, simply do Sequelize.Model.prototype.myMethod = function () { ... }

Depending on the circumstances, you want user instanceof User but also User instanceof Model . It's not possible to have both.

It is possible to have both, User will always inherit from Model, so user instanceof User && user instanceof Model. Basic OOP.

By the way, would x instanceof Sequelize.Model tell you whether x is a model instance (which model unspecified)?

Yes.

@felixfbecker

felixfbecker commented May 13, 2016 •

Copy link
Copy Markdown
Contributor Author

The tests fail because I try to add the name property on the model inside define(), which is not possible in older Node versions because name is the name of the class and define() would return an anonymous class. I tested it on Node 4 and 6, where this works just fine. The only workaround I can see is to either use eval() (bad for performance?) or set _name instead.

@felixfbecker

Copy link
Copy Markdown
Contributor Author

I fixed the issue with the name property, will fallback to using eval() if Function.prototype.name is not configurable. However, there have been commits made to master and Travis will not run a build if the conflicts are not resolved - I cannot easily merge/rebase because I add the whole Instance code manually to model.js and adapt all the properties and instanceof checks. That is a lot of work... @mickhansen Could you trigger a manual build?

@overlookmotel

overlookmotel commented May 14, 2016 •

Copy link
Copy Markdown
Contributor

Depending on the circumstances, you want user instanceof User but also User instanceof Model. It's not possible to have both.

It is possible to have both, User will always inherit from Model, so user instanceof User && user instanceof Model. Basic OOP.

Sorry, I was talking about User instanceof Model not user instanceof Model (note capital U on User).

var User = sequelize.define( 'User', /* blah */ );
assert( User instanceof Sequelize.Model == true );

This will no longer work right? After this PR, you'd have to use User.prototype instanceof Sequelize.Model?

So after this PR, to add a static method to all models, you add a method on Sequelize.Model? Currently:

var myMethod = function () { /* blah */ };
Sequelize.Model.prototype.myMethod = myMethod;
var User = sequelize.define( 'User', /* blah */ );
assert( User.myMethod == myMethod );

After this PR:

var myMethod = function () { /* blah */ };
Sequelize.Model.myMethod = myMethod;
var User = sequelize.define( 'User', /* blah */ );
assert( User.myMethod == myMethod );

Have I got this right? I think this goes a little bit beyond basic OOP!

@overlookmotel

overlookmotel commented May 14, 2016 •

Copy link
Copy Markdown
Contributor

NB Isn't Object.setPrototypeOf() generally bad for performance?

In node v4 and below util.inherits() uses ctor.prototype = Object.create(superCtor.prototype) rather than Object.setPrototypeOf()

@felixfbecker

felixfbecker commented May 15, 2016 •

Copy link
Copy Markdown
Contributor Author

@overlookmotel

This will no longer work right? After this PR, you'd have to use User.prototype instanceof Sequelize.Model ?

Yes.

So after this PR, to add a static method to all models, you add a method on Sequelize.Model ?

Yes. But imo globally patching an imported class from a module is a very bad pattern. The better option, that is now possible, would be if you subclass Sequelize.Model, define your custom methods there, and then let your models extend your custom subclass:

abstract class MyBaseModel extends Sequelize.Model {
  static myStaticMethod() { ... }
  myMethod() { ... }
}
class User extends MyBaseModel { ... }
Model.init(User.name, ...)

And extending classes really is basic OOP. Of course Javascript's prototype concept is a bit hard to grasp, but imo having instances be instances of the model classes is what a user expects.

NB Isn't Object.setPrototypeOf() generally bad for performance?
In node v4 and below util.inherits() uses ctor.prototype = Object.create(superCtor.prototype) rather than Object.setPrototypeOf()

If you look at my code you see I do the same. But that is only so the instances inherit the prototype properties. But you also have make the new Model class inherit the static methods, like find(). util.inherits() actually doesn't care about static properties, but Babel will transpile it that way.
See the _inherits function:

function _inherits(subClass, superClass) {
    if (typeof superClass !== "function" && superClass !== null) {
        throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
    }
    subClass.prototype = Object.create(superClass && superClass.prototype, {
        constructor: {
            value: subClass,
            enumerable: false,
            writable: true,
            configurable: true
        }
    });
    if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}

Since this PR is kind of a breaking change it will land in 4.0... If the decision is made in 4.0 to only support Node 4 and up, that would be awesome, because we could use native classes which of course have better performance.

@overlookmotel

overlookmotel commented May 16, 2016 •

Copy link
Copy Markdown
Contributor

OK, let's start again from the beginning...

I'm not against what you're doing here. I think generally speaking, having an instance of User be instanceof User rather than instanceof User.Instance is a good thing. I was just asking questions to ensure that no functionality gets lost in the process and that performance isn't affected.

I'd say that this should definitely be considered a breaking change - any user code like if (item instanceof Sequelize.Model) { ... } would break - so this should, as you say, land in 4.0.

Concerning OOP, yes user instance User is basic OOP which everyone should understand. It's the part about the User constructor inheriting its static methods from Sequelize.Model which is less standard. But anyway, let's not argue about whether something is "basic OOP" or not. It's difficult to read someone telling you that you're not understanding something "basic" as pretty equivalent to saying "you are an idiot", which isn't a conversation that's going to get us anywhere!

In an app, as you say, it'd be better to subclass Sequelize.Model before modifying it. However, with plugins, the user would generally expect that after applying the plugin, they can use the same objects as before but expect them to exhibit extra functionality. My rule of thumb has been that it's OK for a plugin to shim global Sequelize methods BUT the shims should not change the behaviour of the method unless an option passed to the method explicitly "activates" this new behaviour. So any other instance of Sequelize will behave exactly as before. i.e. the global has been modified but it has no effect by default.

My only real concern about this PR is whether altering the prototype of each model constructor with Object.setPrototypeOf(model, Model) or model.__proto__ = Model is going to impact performance on operations like User.findAll() (which is probably the most often called Sequelize method of all).

My point about Object.setPrototypeOf() not being used in util.inherits() before node v4 wasn't that you should use util.inherits() - that wouldn't work here - but that this may indicate that before node v4 Object.setPrototypeOf() isn't performant. I don't know about this, it's just a guess. Maybe it's still not performant! Certainly MDN contains a pretty stern warning that dynamically setting prototypes is bad for performance.

Anyway, the question of performance will become clearer once Travis starts running.

I'd also suggest adding 2 static methods to Sequelize:

Sequelize.isModel = function(item) { return item && item.prototype instanceof Sequelize.Model; };
Sequelize.isInstance = function(item) { return item && item instanceof Sequelize.Model; };

These could be used internally - easier to understand than item.prototype instanceof Sequelize.Model. Also, these methods could be added now to v3, so users can start transitioning their item instanceof Sequelize.Model code to Sequelize.isModel(item) so it's more v4-ready.

@felixfbecker

Copy link
Copy Markdown
Contributor Author

@overlookmotel I was in no way trying to insult your programming skills. Sorry if I sounded a bit rude, just wanted to answer your questions :)

I would still argue though that a subclass inheriting not only instance methods, but also static methods, is expected behaviour - it's how it works in every other OOP language, the ES6 spec and Babel.

Altering the prototype of an object definitely has a performance impact because it destroys the "prediction" V8 can make about objects. Still, it is the only spec-compliant way to make a class inherit from another. As I said in the original post, this PR is mostly to generate discussion. I would propose to drop support for Node <4 in 4.0 and then use real classes. I'm just a bit worried that 4.0 will take a long time to release. I would rather keep the API changes small (make define() work like before) but clean up the semantics (instance instanceof Model) and make it possible to use classes and decorators for those who want it (I would really like to write a decorator library for Sequelize).

Adding isModel() and isInstance() is a great idea. Maybe isInstance() should be named isModelInstance() though? Because with the 4.0 semantics one could wonder isInstance - instance of what?

@felixfbecker felixfbecker mentioned this pull request May 16, 2016
@overlookmotel

Copy link
Copy Markdown
Contributor

@felixfbecker Yes you're right isModelInstance() is a better name.

Concerning performance, well I guess we'll have to see what impact this has once you've rebased and Travis runs. You still can't subclass Function in newer Javascript versions right? But in my opinion, if this PR heavily impacts performance, that's a bit of a sticking point.

@felixfbecker

Copy link
Copy Markdown
Contributor Author

@overlookmotel well if 4.0 will only support Node >4 I would redo my PR to use classes, and then no Object.setPrototypeOf() or subclassing Function would be necessary. define() would just do

return class extends Model {}

@janmeier

Copy link
Copy Markdown
Member

I think most of what needs to be said has already been said here - I'm just waiting to see the performance impact ;-).

One problem with extending (and overlookmotel might already have mentioned this) is plugins which are working on before / after Define hooks - these will no longer work since there is not define if using classes. But they might be called on Model.init instead ?

@felixfbecker

felixfbecker commented May 19, 2016 •

Copy link
Copy Markdown
Contributor Author

I will make a new PR that uses classes instead of rebasing this (that would be a pain). I originally commited on master (stupid me), I kept the commits in the instance-instanceof-master branch

dan-nyanko added a commit to dan-nyanko/sequelize-to-joi that referenced this pull request Aug 4, 2017
- check instanceof on the prototype see
sequelize/sequelize#5877
- update dependencies
dan-nyanko added a commit to dan-nyanko/sequelize-to-joi that referenced this pull request Aug 4, 2017
- check instanceof on the prototype see
sequelize/sequelize#5877
- update dependencies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants