objection.js icon indicating copy to clipboard operation
objection.js copied to clipboard

Poll - What would you like to see in the future versions of objection?

Open koskimas opened this issue 7 years ago • 63 comments

I'm starting to plan the 2.0 release and I'd like to hear the community's opinions what we should add to objection in 2.0 or later down the road.

I'd like to reiterate here that the goal of objection was never to become Eloquent, Django's ORM, Active Record or any other known ORM. Objection's goal is said pretty well at the top of the github README. Objection is a "query builder on steroids" that never get's in the way of SQL, but still attempts to provide tools for working with repetitive stuff and especially relations.

That said, there are many things those ORMs do better than objection and we should try to bring in the features that suit objection's design goal.

SO, I'd like you to post here what you miss from any other tool you've worked with and think objection should really have. Vote the features using :+1: and :-1:

Couple of things 2.0 will have:

  • A more usable and consistent static hook system that fixes most if not all issues I've seen people having. The instance hooks will still be around. They have their use cases.
  • More consistent naming of methods and concepts. For example eager is used as a verb, even though it's not, joinRelation implies it joins a single relation. joinEager sounds like joinRelation even though it does a very different thing. These will be something like withGraphFetched, joinRelated, withGraphJoined. etc. The old names will remain as aliases at least until 3.0.

https://github.com/Vincit/objection.js/projects/1

koskimas avatar Apr 17 '19 05:04 koskimas

I concede the following is quite niche so feel free to shoot it down :)

One thing I've always missed (and due to that I've implemented myself) is functionality similar to JPA's @Embeddable/@Embedded for logical grouping of related fields in a single table.

If this sounds like something you might want to include in objection I would be more than happy to help you brainstorm and figure out the constraints/logic.

tonisostrat avatar Apr 17 '19 06:04 tonisostrat

@tonisostrat I'll try not to shoot down anything or add my own opinions here too early to not affect the discussion.

koskimas avatar Apr 17 '19 06:04 koskimas

This may be more on the knex-level, but being able to selectively run seeds would be nice.

Also maybe seeing tools like https://github.com/Vincit/knex-db-manager, https://github.com/Vincit/objection-db-errors, and https://github.com/Vincit/objection-find become a part of the core or have better visibility and code examples in the docs, to help folks write less boiler plate initially.

Perhaps those features could be toggled via feature flags by the developer(s).

heisian avatar Apr 18 '19 15:04 heisian

+1 to @heisian 's note for at least https://github.com/Vincit/objection-db-errors (only b/c I'm not familiar with the other 2; thanks for sharing those links, good weekend reading :) ). My coworkers and I have started to default to pulling in that plugin on our projects, really appreciate the extra support on error handling. No opinion / suggestion (helpful or otherwise) on where to go with that, but lowering the barrier to entry for that utility somehow I think would be a really solid addition.

(ps Objection is ill! Thanks for all your work here (and for polling for feedback on v2; looking forward to it))

zemccartney avatar Apr 18 '19 21:04 zemccartney

Would a @column('columnName') property decorator be appropriate? You'd use it to decorate a property of a model and the default (or base class) columnNameMapper would consult this property when performing the mapping.

e.g.

class Singer extends Model {
    static table = 'singer';

    @column('pseudonym')
    name: string;
}

would yield code models with a name property whose value would be used to populate the pseudonym column when a Singer instance is insert()ed, for example.

GreatSchool2 avatar Apr 22 '19 16:04 GreatSchool2

Currently, I work with custom up, down methods in Model classes that I query for all my models to generate a database from scratch, and maintaining the ordering of what should be created first by hand via a simple numbering system.

But I don't ask to implement the management of that at all; I would like however, a way to generate the ordering from relationship graphs, for example.

I also agree with the naming, and would like to see custom behavior for joinRelation also (filters like we have in eager).

ferk6a avatar Apr 30 '19 15:04 ferk6a

I would like:

  1. An option to mix WhereInEagerAlgorithm and JoinEagerAlgorithm in a single query. Thank you for your efforts

venelin-mihaylov avatar May 04 '19 10:05 venelin-mihaylov

Support for for await (...) loops would be nice. Especially if it's backed by cursors. This could fallback to limit/offset, even though that doesn't have the same performance (but still ~constant memory pressure).

for await (let person of People.query()) {
  ...
}

You can kinda get this by using knex stream interface, as Readable streams support asyncIterator since v10.0.0. Though when I did this I had to use People.query().build().stream() which feels a bit clunky.

maxnordlund avatar May 04 '19 15:05 maxnordlund

Currently, I work with custom up, down methods in Model classes that I query for all my models to generate a database from scratch, and maintaining the ordering of what should be created first by hand via a simple numbering system.

But I don't ask to implement the management of that at all; I would like however, a way to generate the ordering from relationship graphs, for example.

I also agree with the naming, and would like to see custom behavior for joinRelation also (filters like we have in eager).

I don't understand.. this library is based on knex which already handles migrations/changelogs, why don't you utilize it?

tonisostrat avatar May 04 '19 19:05 tonisostrat

Currently, I work with custom up, down methods in Model classes that I query for all my models to generate a database from scratch, and maintaining the ordering of what should be created first by hand via a simple numbering system. But I don't ask to implement the management of that at all; I would like however, a way to generate the ordering from relationship graphs, for example. I also agree with the naming, and would like to see custom behavior for joinRelation also (filters like we have in eager).

I don't understand.. this library is based on knex which already handles migrations/changelogs, why don't you utilize it?

In a way, you're right. But I don't like how migrations separate the creation of tables from the Model object itself. It's perhaps a bit more cumbersome, but it's sure convenient!

Regardless, I should probably move to the knex migration way, I think the support for MS SQL is improved now, and it's way better for my own sanity. Thanks!

ferk6a avatar May 05 '19 23:05 ferk6a

I have a handful of thoughts. Given that objection is overall fairly stable and feature-complete, I think the focus should be on using a breaking change (i.e. v2.0) to tighten things up: focus on naming, making any notable alterations to queries, fixing API warts, work on related tooling. You know, things that are worth considering only when there isn't a ton of debt to pay off. It's my impression that there isn't!

I'll just list some ideas, and not so much propose specific solutions, although I'd be happy to talk about solutions if we want to peel-off some additional github issues.

  • Passing arguments to modifiers Currently modify() doesn't directly extend knex's behavior because you can't pass them arguments. I think there's an issue for this https://github.com/Vincit/objection.js/issues/1293. There's an additional inconsistency, where there's no interface for providing arguments to modifiers referenced in relation expressions.

  • Relation modifiers coupled to eager algorithm Currently relation modifiers are implicitly coupled to whichever eager algorithm being used. A given modifier might make sense for the join algorithm but not the where-in algorithm due to the columns that are referenced. I also find myself liberally sprinkling tableRefFor() in these modifiers in order to avoid column name conflicts and make the modifier more generic for use with different eager algorithms. Really not sure how to approach this, but it's something I run into regularly.

  • Conflict between jsonb and join alias separator While there's fantastic support for both jsonb and joins, we currently use : as a separator for both, which sometimes leads to funky workarounds like overriding the separator in defaultEagerOptions.

  • Consider standardizing validators to implement tableMetadata() More often than not our validations directly inform table metadata, and I think if there were a blessed way for validators to implement tableMetadata() (and the built-in ajv validator providing this option), then we could remove this rare instance that we rely on some stateful magic. This might also lead to nice things like the often-desired ability to "select all columns but x, y, z."

  • Make relation and unrelation more ergonomic Typically relate() and unrelate() chain off of a model instance's $relatedQuery(), which means that one has to obtain a model instance to use these methods. I've used workarounds that look like this. There are a few different directions to explore to alleviate this, but I think there could be some really interesting options to make relatedQuery() more active, and not necessarily relegated solely to subqueries.

    // Fetch
    await Person.query().findById(1)
        .relatedQuery('pets').where('name', 'Fluffy');
    
    // Unrelate
    await Person.query().findById(1)
        .relatedQuery('pets').findById(42)
        .unrelate();
    
  • Consider folding objection-db-errors into core I can only echo my colleague: https://github.com/Vincit/objection.js/issues/1302#issuecomment-484692000. We use this all the time and it's a better error-handling experience!

  • Focus on tooling and plugins This is partly on the community too, but I would love to see more quality plugins appear, especially for modeling common application features. @faustbrian has done a neat job with this in the Laravel community. Imagine plugins like "taggable", "commentable", "followable", "likeable", etc. Objection v2.0 may be able to help by considering how validation works in some of these complex cases, i.e. when a community plugin needs to play nice with existing models that may use one of several validators (we use a joi validator rather than ajv, for example). On the topic of tooling, generating knex migrations from objection models/validators is also of interest.

devinivy avatar May 06 '19 02:05 devinivy

@devinivy Thanks! You have alot of great ideas there.

Passing arguments to modifiers

This will be fixed at least for the modify function's part. I'd like allow arguments for modifiers in relation expressions too. Once modify is fixed for named modifiers, you can at least do this:

class Pet extends Model {
  static get modifiers() {
    return {
      onlySpecies: (query, species) => query.where('species', species)
    }
  }
}

Person
  .query()
  .eager('[pets, children.pets(onlyDogs)]', {
    onlyDogs: query => query.modify('onlySpecies', 'dogs')
  })

That's still pretty verbose, but it allows you to "bind" arguments to existing modifiers. What do you think? Could that be enough? Another option would be a mechanism like this:

Person
  .query()
  .eager('[pets, children.pets(onlyDogs)]')
  .bindModifier('onlySpecies', 'onlyDogs', 'dogs')

but is that really better? It intruduces yet another concept.

We could also add helpers like these:

Person
  .query()
  .eager('[pets, children.pets(onlyDogs)]', {
    onlyDogs: bindModifier('onlySpecies', 'dogs')
  })

@devinivy Do you have any other ideas for this?

I've also thought about making modifiers query-wide, so that they could be used with joinRelation etc. So instead of this

Person
  .query()
  .eager('[pets, children.pets(onlyDogs)]', {
    onlyDogs: query => query.modify('onlySpecies', 'dogs')
  })

you'd say this:

Person
  .query()
  .eager('[pets, children.pets(onlyDogs)]'),
  .modifiers({
    onlyDogs: query => query.modify('onlySpecies', 'dogs')
  })

Relation modifiers coupled to eager algorithm

This is a tricky one. I also hate that this happens. That's one of the reasons why I'll deprecate the defaultEagerAlgorithm and eagerAlgorithm() proerties and methods. You need to explicitly use withGraphFetched or withGraphJoined to make it clearer that you are using a completely different algorithm.

Fixing this would again require objection to duplicate the knex API which I've been trying to avoid. We would need to wrap all where*, groupBy, join* etc. methods, parse the inputs and basically build an AST tree to be able to figure out what the user means when he/she uses column name in a query. Is it from a joined table? Is it from a parent query in a subquery situation? The MVP solution would be to wrap all where methods and automatically add ${tableRefFor(modelClass)}.column for each column that doesn't have an explicit table, but that would already require objection to duplicate and test the where API of knex.

If you have any good ideas, I'm all ears.

One thing we could do is add a Model.ref function that makes it cleaner to use tableRefFor. Model actually already has that, but it's not public yet. It allows you to do this:

class Person extends Model {
  static modifiers = {
    boys: query => {
      const ref = Person.ref
      query.where(ref('gender'), 'male').where(ref('age'), '<', 18)
    }
  }
}

Conflict between jsonb and join alias separator

This is another complete design flaw I'll be addressing. We can use -> as a separator for either the json references or the joinEager aliases. Which one would you prefer?

Consider standardizing validators to implement tableMetadata()

The Validator API is bad. This is a good idea, but overriding validators doesn't seem to be that common, so I'll probably leave this for later (3.0?) unless you'd like to take a stab at this problem @devinivy? You guys have probably written the most comprehensive custom validator in schwifty.

Make relation and unrelation more ergonomic

// Fetch
await Person.query().findById(1)
    .relatedQuery('pets').where('name', 'Fluffy');

// Unrelate
await Person.query().findById(1)
    .relatedQuery('pets').findById(42)
    .unrelate();

I agree with the title, but not with either of these examples. They would be confusing. The .relatedQuery('pets') in those calls completely changes the query. a where call before that affects the parent query, while where after it affects the "child" query. I'd rather just make creating model instances from just a relation property (primary key most of the time) easier. Something like this:

await Person.fromId(1).$relatedQuery('pets').where('name', 'Fluffy');
await Person.fromId(1).$relatedQuery('pets').findById(42).unrelate()

Consider folding objection-db-errors into core

Will be done. This was also brought up by @heisian

Focus on tooling and plugins

This is pretty vague. I'd like to see more plugins and 3rd party tools, but I don't know how to help there. The Validator interface is one thing, but I don't think that is the biggest limiting factor right now.

koskimas avatar May 18 '19 07:05 koskimas

It's only a small feature, but how about a method called $loadRelatedUnlessLoaded, which is like Model#$loadRelated but doesn't load any data which is already in the object.

To see why this is useful, consider the following function.

async function f(user) {
  const u = user.$clone();
  await u.$loadRelatedUnlessLoaded('favouriteBook.author');
  // Do something with u.favouriteBook.author
}

I want to be able to pass a User object to f without having to care about which relations have been loaded. But if I call $loadRelated in f, then the application is doing unnecessary work if the data has already been loaded.

$loadRelatedUnlessLoaded may not be a good name; feel free to think of a better one.

phormio avatar May 25 '19 17:05 phormio

@phormio That's a good idea :+1: That has been requested before.

$loadRelated will be replaced by $fetchGraph in 2.0 (the old name will remain at least until 3.0). $fetchGraph will take an options object as the second argument. We can add an option for this. Something like

await u.$fetchGraph('favoriteBook.author', { reloadExisting: false })

koskimas avatar May 25 '19 20:05 koskimas

@koskimas thanks for the thoughtful response 🙏

Passing arguments to modifiers

I like the example you gave, and I think that's totally fine! I like the bindModifiers() helper too :) Not a huge fan of the query-wide eager modifiers but also not so hard against it, especially if the current interface remains in existence.

Relation modifiers coupled to eager algorithm

I agree, I think this is a really hard problem to solve and it's not easy to justify the effort. Going down that path would generate a lot of questions that I don't have answers to. I would be afraid of making the generated queries harder to control and more opaque. Making tableRefFor() more friendly sounds like it's low-hanging fruit, and would be a nice improvement. I would be happy to contribute a section to the docs that addresses this—I get the sense that a lot of people run into this issue then avoid it rather than solve it since tableRefFor() doesn't have a lot of visibility in the docs.

Conflict between jsonb and join alias separator

Would -> make a better separator for jsonb or joinEager aliases? Hmm... that's hard for me to say. I struggle with the idea of using that as a separator since it's so close in meaning to postgres's own jsonb operator. If I had to choose one, I think I would suggest using it for jsonb. Is ~> too weird? I don't have a full understanding of knex's limitations here, but another option might be to see what it would take to loosen those limitations in knex.

Consider standardizing validators to implement tableMetadata()

I'll look into it!

Make relation and unrelation more ergonomic

Fair! I don't think these two options are mutually exclusive, and the example you gave is totally straightforward / would be a nice improvement. At the same time it does feel a little "off" to me that in order to build some queries I need to create a model instance with some fields filled-in. It works, but it doesn't seem super objection-y (obviously this is just a matter of opinion—whatever you decide is "objection-y" by definition!) . I still think an API similar to what I proposed would be in the spirit of objection as it relates to query laziness and composability. Does it seem more reasonable if it's re-written in steps?

/* select * from users where type = 'musician' */
const musicians = User.query().where('type', 'musician');

/* select * from animals where
     type = 'dog' and
     "ownerId" in (select "ownerId" from users where type = 'musician') */
const musiciansDogs = musicians.relatedQuery('pets').where('type', 'dog');

/* update animals set "ownerId" = null where
     type = 'dog' and
     "ownerId" in (select "ownerId" from users where type = 'musician') */
const unrelateMusiciansFromDogs = musiciansDogs.unrelate();


// An alternative idea, just for fun.

const musicians = User.query().where('type', 'musician');
const musiciansDogs = User.relatedQuery('pets').per(musicians).where('type', 'dog');
const unrelateMusiciansFromDogs = musiciansDogs.unrelate();

Consider folding objection-db-errors into core

👍

Focus on tooling and plugins

Agree I was pretty vague there. I'm mostly trying to think of things that could fragment efforts to write generic tooling for objection, so that they can be squashed proactively in v2. Maybe there's not a lot in the way!

devinivy avatar May 27 '19 15:05 devinivy

It's only a small feature, but how about a method called $loadRelatedUnlessLoaded, which is like Model#$loadRelated but doesn't load any data which is already in the object.

To see why this is useful, consider the following function.

async function f(user) {
  const u = user.$clone();
  await u.$loadRelatedUnlessLoaded('favouriteBook.author');
  // Do something with u.favouriteBook.author
}

I want to be able to pass a User object to f without having to care about which relations have been loaded. But if I call $loadRelated in f, then the application is doing unnecessary work if the data has already been loaded.

$loadRelatedUnlessLoaded may not be a good name; feel free to think of a better one.

This would be such a useful feature to have and reduce many unneeded queries!

chalcedonyt avatar Jun 14 '19 05:06 chalcedonyt

@caiquecastro That's a good idea. @phormio Could you create a separate issue about that feature? That's something we can add after 2.0 since it's not breaking.

koskimas avatar Jun 14 '19 17:06 koskimas

@koskimas, I was actually quite happy with your own suggestion. However, I've opened a new issue asking for Model#$loadRelatedUnlessLoaded.

phormio avatar Jun 15 '19 10:06 phormio

A small list I can think about to upvote some suggestions:

  • add db-errors to core. Super useful library a lot of users will appreciate
  • move to using native stuff, e.g. Bluebird -> Promise, lodash -> native functions, etc. This is already in todo list
  • drop node 6 support, use >= 8. Seems to be done from todo list
  • validation feels weird. I had an issue with nested models (https://github.com/Vincit/objection.js/issues/478), moved to validation outside of objection. Maybe something has changed, but this was an issue. I also use another validation library (yup)

This is probably all I can think about, objection gives a joy using database and I'll recommend using it instead of other orms any day. Thank you for it ❤️

vladshcherbin avatar Jun 16 '19 13:06 vladshcherbin

What about setting useLimitInFirst to true by default ? Docs say: Defaults to false for legacy reasons.

Any downsides/cons? 🤔

vladshcherbin avatar Jun 16 '19 22:06 vladshcherbin