Skip to content

Proposal for improving FindOptions #4280

Closed

Description

@haschu

Issue type:

[ ] question
[ ] bug report
[x] feature request
[ ] documentation issue


I'd like to implement some improvements for the Find Options and want to discuss them before I submit a PR.

1. Support nested where in combination with relations (See: #3902, #3890)

It seems to me that TypeORM only supports nested where statements in combination with embedded entities, or am I wrong?

It would be nice to have such a feature while dealing with relations.

I would suggest either:

userRepository.find({
  relations: ["photo"],
  where: {
    photo: {
      format: "png"
    }
  }
});

or

userRepository.find({
  relations: ["photo"],
  where: {
    "photo.format": "png"
  }
});

2. Support partial select for relations

Currently, when using relations: ["photo"], TypeORM uses leftJoinAndSelect() which selects all columns from photo.

Maybe we could do something like:

userRepository.find({
  relations: [
    {
      name: "photo",
      select: ["format", "createdAt"]
    },
    // Stay backwards compatible
    "something.else"
  ]
});

3. Add possibility to extend generated queries with QueryBuilder

That solution would be easy to implement:

userRepository.find({
  where: [
    { firstName: "Timber", lastName: "Saw" },
    { firstName: "Stan", lastName: "Lee" }
  ],
  query: (qb) => {
    // Do some stuff with `QueryBuilder` that isn't supported by 
    // FindOptions
  }
});

Of course one could use QueryBuilder in the first place, but then you have to re-implement all those handy generations from find methods. The docs should make clear that something like qb.execute() or qb.getOne() shouldn't be used, although it makes no sense anyway.

4. Support custom find operators

Currently, the creation logic of all find operators is hard coded in FindOperator.
We could easily refactor this by passing a callback to FindOperator, e.g.:

export function CustomEqual<T>(value: T|FindOperator<T>) {
  return new FindOperator(
      (
        connection: Connection, 
        aliasPath: string, 
        parameters: string[]
      ) => {
          return `${aliasPath} = ${parameters[0]}`;
      }, 
      value
  );
}

Maybe FindOperator could be refactored a little bit more - for example connection is passed to toSql() but isn't used.


@pleerock I would appreciate if you'd find some time to give your input :)

Since you mentioned that you'll refactor QueryBuilder in the future, I would stay out of the QueryBuilder code and try to implement everything within the Find Options, e.g. FindOptionsUtils - also point 1.

Activity

  1. Kononnable commented on Jun 23, 2019

    @Kononnable
    Contributor

    and try to implement everything within the Find Options, e.g. FindOptionsUtils

    Make sure you take a look at @next implementation of FindOptions, there is a lot changed there and I'm not sure everything would be possible outside of QueryBuilder.

    As for the proposal - number 3 might be a tricky one. In @next one .find might results in multiple queries to db(where relations are passed). When 'old relations system'(which uses single query) will be reimplemented in @next user would be able to choose which approach he wants to use(both have some advantages and disadvantages).
    Anyhow, even with 'old relations' I'm not sure we should implement it like that. Wouldn't it be easier to just generate a query builder based on object passed in FindOptions and instead of returning entities return QueryBuilder, so user can do with it what he wants? Not sure how we could call such method.

  2. haschu commented on Jun 24, 2019

    @haschu
    ContributorAuthor

    I wasn't aware of @next- thanks for pointing out. Should I implement those features on the @next branch then? And if so, when can we expect the changes to be merged into master? I guess not anytime soon, or? (over 300 commits behind master)

    Anyhow, even with 'old relations' I'm not sure we should implement it like that. Wouldn't it be easier to just generate a query builder based on object passed in FindOptions and instead of returning entities return QueryBuilder, so user can do with it what he wants? Not sure how we could call such method.

    I also considered that solution - imho there are two options:

    1. Introduce a "sibling" method for each find method, e.g. findOne() and findOneAndGetQB()
    2. Introduce an option which indicates, that the find methods should return QueryBuilder instead of entities (I don't like that)

    All other solution that come to my mind would introduce lots of breaking changes which should be avoided. What do you think?

  3. haschu commented on Jul 4, 2019

    @haschu
    ContributorAuthor

    @pleerock, any thought on this? :)

    Are those proposed features acceptable for a PR?
    For me, point 1 & 2 are having the most priority.

    Regarding point 1 - I think a few adjustments in QueryBuilder will be necessary, but not too much.

  4. lsmialowski commented on Jul 9, 2019

    @lsmialowski

    Fingers crossed for points 1 and 2 :)

  5. stellarbear commented on Nov 12, 2019

    @stellarbear

    Hope for nested where

  6. Firaenix commented on Mar 31, 2020

    @Firaenix
  7. javierlinked commented on Jun 23, 2020

    @javierlinked

    It seems like nop.

  8. Firas1993 commented on Sep 14, 2020

    @Firas1993

    it seems we are forced to use the queryBuilder here ?

  9. haschu commented on Oct 6, 2020

    @haschu
    ContributorAuthor

    @imnotjames Just noticed the new "new feature" label. Does that mean the proposal has been accepted and is open for a PR?

  10. imnotjames commented on Oct 6, 2020

    @imnotjames
    Contributor

    This means it's a feature request, nothing more. If you want to open a PR you always can

  11. haschu commented on Oct 6, 2020

    @haschu
    ContributorAuthor

    @imnotjames Before I invest the time and effort, I'd like to make sure which of the proposed features are actually acceptable for the maintainers :)
    That's why I opened this issue in the first place. I guess the most requested feature would be nested where statements.

  12. imnotjames commented on Oct 15, 2020

    @imnotjames
    Contributor

    Ok - looking at this issue --

    1. Support nested where in combination with relations (See: Find options nested where  #3902, Nested relations filtering doesn't work #3890)

    ✔️ Already supported

    I tested it and this seems to work, not sure where you're seeing it isn't. See #2707 & comment there if you believe it's not working.

    1. Support partial select for relations

    ❌ Not yet supported

    This will break a lot of assumptions made throughout the codebase. Why make this change? It'd be easier to discuss in its own issue if you think it's a very important extension to the FindOptions

    1. Add possibility to extend generated queries with QueryBuilder

    ❌ Not yet supported

    You should be able to use many of the find options within various parts of the query builder. Please use that instead as it simplifies the API. If you believe this should be brought in can you find examples of similar APIs we can build off of for this?

    Because query builders have global namespaces, etc, it could break a lot of assumptions to let it be modified directly.

    1. Support custom find operators

    ✔️ Already supported

    You can create custom FindOperators with the Raw operator in the next release, as it supports parameters.

    For example, a fancy shmancy JSON path comparator:

    const JSONPath = (path: string[], value) => Raw(alias => '${alias}->${path.join('->')} = :json_value', { json_value: value });
    
    const matches = await repo.find({ blobby: JSONPath(['foo', 'bar'], "Hello World") });
    

    (ps that's off the top of my head, haven't tested it so don't just copy/ paste it directly.)

  13. self-assigned this
    on Oct 15, 2020
  14. amadeus-torwell commented on Nov 6, 2020

    @amadeus-torwell
    1. I tried to use it on many-to-many relations with custom properties and it does not seem to work with that. How did you test it @imnotjames?
  15. imnotjames commented on Jul 4, 2021

    @imnotjames
    Contributor
    1. I tried to use it on [many-to-many relations with custom properties](https://github.com/typeorm/typeorm/blob/master/docs/many-to-many-relations.md#many-to-many-relations-with-custom-properties) and it does not seem to work with that. How did you test it @imnotjames?
    

    It worked in some relations cases but not all.

  16. pleerock commented on Mar 27, 2022

    @pleerock
    Member

    I think everything proposed in this PR already supported in 0.3.0. I'll close this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions