-
-
Notifications
You must be signed in to change notification settings - Fork 807
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Respect negative conditions for collection associations #645
Respect negative conditions for collection associations #645
Conversation
Yes I'm fixing mongoid... 🔨 |
When a collection association (has_many, etc) is searched for negative conditions (NOT...), a JOIN will still include other rows that match. The implied meaning is that it should only select where *none* of the associations match, but the actual result still selects records where *any* of the joined associations match. This implementation removes joins that were added while building the conditions and moves them into a subquery if needed.
a131fa2
to
7f1235a
Compare
Respect negative conditions for collection associations + refactoring.
Awesome 🎉 great work @avit 💜 |
Fixes #381. |
@jonatack Thanks for the merge on this. I have one more thing to add: the "NOT NULL" predicate still needs to be handled specially. I will add another PR for this. |
Hey @avit thank you very much for your work on this. I was trying to use this functionality with conditional In my case:
Then
I'm sorry to hijack this old thread but I was wondering if: a) you know of a way to make this query work Many thanks for any insights! |
When searching against attributes from a collection association (
has_many
/:through
/has_and_belongs_to_many
), a normal JOIN will include false positives when asking to exclude values (!=
,NOT IN
,IS NOT NULL
) and another tuple is matched.This is the basic case, see specs for details:
In situations where this would happen, I've moved the
LEFT OUTER JOIN
into a subquery with inverted conditions. This is implemented with a correlated primary key which should help the query plan to avoid scanning entire tables in the subquery. The conditions now look like this:Note that root.id is referenced in the inner query. The EXPLAIN query plan for this looks sensible, at least in MySQL where I explored it.
As far as I know this works with all standard ActiveRecord joins: I have not yet verified with composite keys or polymorphic joins or Nth-degree associations but it should be close to working if it isn't already.
I will start testing this against our own real-world data to see how it performs, please check it out too.
Known issues:
not_null
predicate: seems like a positive case and should use the original code branch.