Skip to content

Rewrite include in findAll, findOne, findAndCountAll  #15260

Description

@ephys

Feature Description

findAll (and by extension, findOne and findAndCountAll) has a very large number of issues. @ephys' research on SELECT queries has been used to document and research them.

Describe the feature you'd like to see implemented

The majority of issues come from how include works. It tries to cover the use cases of both joins and subqueries, and as a result often breaks in unexpected ways due to incompatible options and the fact that the user has little understanding of when a JOIN is used VS a subquery.

The new API's first goal would be to restrict the scope of include to a set of features that are compatible with BOTH join and subqueries. If the user needs to use a JOIN clause, a dedicated join option has been added. If the user needs to use a subquery, a dedicated subquery has been added. join, include, and subquery can all be used together in predictable ways.

I've documented how the new API would work. It is available here: https://6349415a5218b826a3409349--sequelize-site.netlify.app/docs/v7/core-concepts/querying/

Is this feature dialect-specific?

  • No. This feature is relevant to Sequelize as a whole.

Would you be willing to resolve this issue by submitting a Pull Request?

  • Yes, I have the time and I know how to start.

Indicate your interest in the addition of this feature by adding the 👍 reaction. Comments such as "+1" will be removed.

Activity

  1. added
    type: feature
    on Nov 8, 2022
  2. self-assigned this
    on Nov 8, 2022
  3. nicoabie commented on Nov 23, 2022

    @nicoabie

    @ephys "@ephys' research on SELECT queries" cannot be accessed. Maybe it is a private route?

    I've noted the following behavior:

    Model.findOne({where: { [Op.and]: [{cond1}, {cond2}] }, include}) generates a subquery
    Model.findOne({where: { cond1, cond2 }, include}) does NOT generate a subquery
    Model.findAndCountAll does NOT generate a subquery in both cases

    Would it be possible to make Model.findOne({where: { [Op.and]: [{cond1}, {cond2}] }, include}) not generate a subquery in v6?

    I think it wouldn't be a breaking change

  4. ephys commented on Nov 23, 2022

    @ephys
    MemberAuthor

    I've just made it visible, but it's not very useful. It's just a list of issues

    The second part of your request isn't really related to this issue. I think such a change would be a breaking change, but if you open a new issue with a complete example we can investigate it further

  5. evanrittenhouse commented on Nov 24, 2022

    @evanrittenhouse
    Contributor

    @ephys if you need help with this let me know, would love to help out with design and implementation. Was also thinking about a larger 'model.js' refactor anyway - the file is super unwieldy and hard to work with for new contributors. It'd obviously be a huge undertaking but this could be a good step towards that. Thoughts?

  6. ephys commented on Nov 25, 2022

    @ephys
    MemberAuthor

    In terms of design, don't hesitate to take a look at https://6349415a5218b826a3409349--sequelize-site.netlify.app/docs/v7/core-concepts/querying/. I think it's super important to make sure our design is sound and covers as many use cases as possible

    For implementation, I'm thinking of doing it in multiple phases:

    1. Implement a new method in QueryGenerator _experimental_selectQuery, which will eventually replace selectQuery. Making sure it always produces the right query.
    2. Implement QueryInterface#_experimental_select, which should handle things like executing the query & mapping the result to the model
    3. Finally, Model._experimental_findAll, and Model._experimental_findOne

    Then we'll need to look into Model.count, so Model.findAndCountAll can use the new API too.

    With the current state of selectQuery, and findAll, I'm honestly thinking of writing them from scratch

  7. WikiRik commented on Nov 25, 2022

    @WikiRik
    Member

    I think a good starting point would be to overhaul the selectQuery test suite to cover may more cases. And especially unifying these tests since currently they all have dialect-specific unit tests (see postgres here for example). Maybe that's something you can take a look at? @evanrittenhouse

  8. ephys commented on Nov 25, 2022

    @ephys
    MemberAuthor

    Since we're going for a complete rewrite, we won't be using the same test suites. I think we'll copy the ones that are still good as we develop QueryGenerator#_experimental_selectQuery. We'll try to develop that method progressively: First the basics (select attributes from table where x), then add support one by one for GROUP BY, LIMIT, ORDER BY, joins, and subqueries. By doing it slowly in multiple PRs, we can make sure we're adding all the relevant unit tests

  9. ephys commented on Nov 25, 2022

    @ephys
    MemberAuthor

    To add a bit more: In a future release we'll make _experimental_selectQuery the default selectQuery and the current selectQuery will be renamed to legacySelectQuery or something like that. It won't receive any further updates but it should make migrating a little bit easier

  10. ephys commented on Mar 3, 2023

    @ephys
    MemberAuthor

    A few notes for a future design update:

    • Can (and how) group by work with this design, or should we not include it and move that to the raw query builder API? Should we ban it from being used with include (can still be used with join)? Should we require group by on models to include at least one unique index (or PK) so we can identify the model (everything else would be done via the raw query builder)?
    • How can we support DISTINCT, and DISTINCT(x)
    • Add required to include if possible. In non-subquery mode, it produces an INNER JOIN which works fine. In subquery mode (limit is specified), it should probably include the where condition inside of the subquery, as another subquery, like this:
      User.findAll({
        include: {
          association: 'projects',
          where: {
            name: 'project 1',
          },
          required: true,
        },
        limit: 10,
      })
      would produce
      SELECT u.* FROM (
        SELECT * FROM users 
        -- include required must run before limit
        WHERE id IN (
          SELECT DISTINCT user_id FROM projects
          WHERE name = 'project 1'
        )
        LIMIT 10
      ) u
      LEFT JOIN projects p
        ON p.user_id = u.id
       -- The where inside the include must also filter the include
       AND p.name = 'project 1'
      If required were false, it would produce this instead:
      SELECT u.* FROM (
        SELECT * FROM users 
        LIMIT 10
      ) u
      LEFT JOIN projects p
        ON p.user_id = u.id
       -- The where inside the include must also filter the include
       AND p.name = 'project 1'
      Without limit, it would produce this:
      SELECT u.* FROM users u
      LEFT JOIN projects p
        ON p.user_id = u.id
       -- The where inside the include must also filter the include
       AND p.name = 'project 1'
    • required should always be false by default

    A few notes for the future implementation:

    • If a user tries to reference an alias that is either not loaded, has a typo, or can't be accessed, Sequelize needs to throw an error early instead of producing a broken query.
    • This is also true for trying to reference a VIRTUAL attribute, the error needs to explain that virtual attributes cannot be used in queries
    • If the user tries to use a BelongsToMany association as their ON clause in a join, we need to throw an error explaining that they can't, but that they can use the association to the through then the association from through to target instead (include actual association names)
  11. added theissue type on Mar 9, 2025
  12. 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

Labels

No labels
No labels

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions