Skip to content

has[Association]() makes a complete INNER JOIN SELECT - should be lightweight confirmation, proof and solution #10514

Closed

Description

@the-vampiire

What are you doing?

Using the has[Association]() method on a Model instance

...Model defs...

ModelA.belongsToMany(models.ModelB, { through: ModelC });
ModelB.belongsToMany(models.ModelA, { through: ModelC });

...create entries...

instanceA.hasB(instanceB);

What do you expect to happen?

When a has[Association]() method is called that a lightweight (0 attributes) SELECT is made to confirm the association without wasting resources.

What is actually happening?

Calling has[Association]() makes a heavy INNER JOIN SELECT query.

  • selects all attributes from the associated table and the join table
  • none of the selected attributes are returned / used
  • since the method returns a boolean true or false (confirmation method) this big SELECT is pointless

calling instanceA.hasB(instanceB) results in the following SQL echo:

Executing (default): SELECT "ModelB"."id", "ModelB"."email", "ModelB"."first_name", "ModelB"."last_name", "ModelB"."company", "ModelB"."created_at", "ModelB"."updated_at", "ModelC"."id" AS "ModelC.id", "ModelC"."paid" AS "ModelC.paid", "ModelC"."created_at" AS "ModelC.created_at", "ModelC"."updated_at" AS "ModelC.updated_at", "ModelC"."a_id" AS "ModelC.a_id", "ModelC"."b_id" AS "ModelC.b_id" FROM "bs" AS "ModelB" INNER JOIN "cs" AS "ModelC" ON "ModelB"."id" = "ModelC"."b_id" AND "ModelC"."a_id" = 50 WHERE ((("ModelB"."id" = 97)));

Temporary Solution

correct boolean result returned when modifying call as

  • instanceA.hasB(instanceB, { attributes: [], joinTableAttributes: [] });
  • now makes a lightweight SELECT:
Executing (default): SELECT  FROM "bs" AS "ModelB" INNER JOIN "cs" AS "ModelC" ON "ModelB"."id" = "ModelC"."b_id" AND "ModelC"."a_id" = 50 WHERE ((("ModelB"."id" = 97)));

Suggestion

Change internal behavior of has[Association]() method calls to use options object { attributes: [], joinTableAttributes: [] } so that this operation does not perform such a heavy query.

Output, either JSON or SQL

Dialect: postgres (but I believe any should be affected)
Dialect version: 9.6.10
Database version: 9.6.10
Sequelize version: 4.43.0
Tested with latest release: No (If yes, specify that version)

Note : Your issue may be ignored OR closed by maintainers if it's not tested against latest version OR does not follow issue template.

Activity

  1. the-vampiire commented on Mar 6, 2019

    @the-vampiire
    Author

    where to change: lib/associations/belongs-to-many.js line 476

    • add attributes: [], joinTableAttributes: []
    • also modify JSDoc first @param

    modified:

    /**
       * Check if one or more instance(s) are associated with this. If a list of instances is passed, the function returns true if _all_ instances are associated
       *
    X   * @param {<Model>} sourceInstance source instance to check for an association with
       * @param {<Model>|<Model>[]|string[]|string|number[]|number} [instances] Can be an array of instances or their primary keys
       * @param {Object} [options] Options passed to getAssociations
       *
       * @returns {Promise<boolean>}
       */
      has(sourceInstance, instances, options) {
        const where = {};
    
        if (!Array.isArray(instances)) {
          instances = [instances];
        }
    
        options = Object.assign({
          raw: true
        }, options, {
          scope: false,
    X      attributes: [],
    X      joinTableAttributes: [],
        });
    
        where[Op.or] = instances.map(instance => {
          if (instance instanceof this.target) {
            return instance.where();
          }
          return {
            [this.target.primaryKeyAttribute]: instance
          };
        });
    
        options.where = {
          [Op.and]: [
            where,
            options.where
          ]
        };
    
        return this.get(sourceInstance, options).then(associatedObjects => associatedObjects.length === instances.length);
    }

    sorry I don't know how to make contributions to open source projects. if anyone can tell me the steps I'd be happy to introduce this fix.

  2. changed the title [-]has[Association] makes a complete INNER JOIN SELECT - should be lightweight[/-] [+]has[Association] makes a complete INNER JOIN SELECT - should be lightweight confirmation, proof and solution[/+] on Mar 7, 2019
  3. changed the title [-]has[Association] makes a complete INNER JOIN SELECT - should be lightweight confirmation, proof and solution[/-] [+]has[Association]() makes a complete INNER JOIN SELECT - should be lightweight confirmation, proof and solution[/+] on Mar 7, 2019
  4. added
    performance
    on Mar 9, 2019
  5. the-vampiire commented on Mar 9, 2019

    @the-vampiire
    Author
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

    performance

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions