-
Notifications
You must be signed in to change notification settings - Fork 1.4k
MONGOID-5057 Add support for has_many :through
#6151
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
Open
jamis
wants to merge
21
commits into
mongodb:master
Choose a base branch
from
jamis:5057-has_many-through
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
854de86
MONGOID-5057 Add ReadonlyAssociation error class
jamis cf23a93
MONGOID-5057 Add YARD docs to ReadonlyAssociation#initialize
jamis 43e0ba1
MONGOID-5057 Add THROUGH_MACRO_MAPPING and :through routing in define…
jamis 1832ade
MONGOID-5057 Fix ASSOCIATION_OPTIONS and add validation_default in th…
jamis 485ba7b
MONGOID-5057 Implement HasOneThrough metadata, proxy, and eager loader
jamis 1793887
MONGOID-5057 Add stores_foreign_key? and clarify criteria/group_by_ke…
jamis 40fb663
MONGOID-5057 Add has_one :through integration tests and embedded guar…
jamis 8ccdc6e
MONGOID-5057 Strengthen has_one :through integration tests (source op…
jamis f0768d4
MONGOID-5057 Implement HasManyThrough metadata, proxy, and eager loader
jamis c266612
MONGOID-5057 Clarify criteria vs resolve on HasManyThrough
jamis f858297
MONGOID-5057 Add has_many :through integration tests
jamis 15378d8
MONGOID-5057 Fall back to preload in eager_load for :through associat…
jamis 29ed396
MONGOID-5057 Clarify eager_load fallback warning when mixed inclusion…
jamis 2e66baa
MONGOID-5057 Add eager loading integration tests for :through associa…
jamis 298ca1f
MONGOID-5057 Add :source option integration test
jamis 41697e1
MONGOID-5057 Fix HasManyThrough#criteria to accept base and return sc…
jamis 7d7d122
Merge branch 'master' into 5057-has_many-through
jamis 882e793
Add :order option, and disallow HABTM as a source for has_any :through
jamis 0ff8a0e
MONGOID-5057 Address code review feedback on through associations
jamis 178cbc4
MONGOID-5057 Replace em-dashes in context descriptions with ASCII hyp…
jamis ef2852f
Merge branch 'master' into 5057-has_many-through
jamis File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,187 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| require 'mongoid/association/referenced/has_many_through/proxy' | ||
| require 'mongoid/association/referenced/has_many_through/eager' | ||
|
|
||
| module Mongoid | ||
| module Association | ||
| module Referenced | ||
| # Metadata class for has_many :through associations. | ||
| class HasManyThrough | ||
| include Relatable | ||
|
|
||
| # The options available for this type of association, in addition to the | ||
| # common ones. | ||
| # | ||
| # @return [ Array<Symbol> ] The extra valid options. | ||
| ASSOCIATION_OPTIONS = %i[order source through].freeze | ||
|
|
||
| # The complete list of valid options for this association, including | ||
| # the shared ones. | ||
| # | ||
| # @return [ Array<Symbol> ] The valid options. | ||
| VALID_OPTIONS = (ASSOCIATION_OPTIONS + SHARED_OPTIONS).freeze | ||
|
|
||
| # The list of association complements. | ||
| # | ||
| # @return [ Array ] | ||
| def relation_complements | ||
| [].freeze | ||
| end | ||
|
|
||
| # Setup instance methods on the owner class. | ||
| # | ||
| # @return [ self ] | ||
| def setup! | ||
| setup_instance_methods! | ||
| self | ||
| end | ||
|
|
||
| # Is this association embedded? | ||
| # | ||
| # @return [ false ] | ||
| def embedded? | ||
| false | ||
| end | ||
|
|
||
| # The proxy class for this association type. | ||
| # | ||
| # @return [ Class ] | ||
| def relation | ||
| Proxy | ||
| end | ||
|
|
||
| # Through associations never store a foreign key on the owner document. | ||
| # | ||
| # @return [ false ] | ||
| def stores_foreign_key? | ||
| false | ||
| end | ||
|
|
||
| # The intermediate association metadata on the owner class. | ||
| # Resolved lazily to allow forward references. | ||
| # | ||
| # @return [ Mongoid::Association::Relatable ] | ||
| def through_association | ||
| @through_association ||= begin | ||
| assoc = @owner_class.relations[@options[:through].to_s] || | ||
| raise( | ||
| Errors::InvalidRelationOption.new( | ||
| @owner_class, name, :through, @options[:through] | ||
| ) | ||
| ) | ||
| if assoc.embedded? | ||
| raise( | ||
| Errors::InvalidRelationOption.new( | ||
| @owner_class, name, :through, | ||
| 'through association must be a referenced association, not embedded' | ||
| ) | ||
| ) | ||
| end | ||
| assoc | ||
| end | ||
| end | ||
|
|
||
| # The source association metadata on the intermediate class. | ||
| # Resolved lazily to allow forward references. | ||
| # | ||
| # @return [ Mongoid::Association::Relatable ] | ||
| def source_association | ||
| @source_association ||= begin | ||
| source_name = (@options[:source] || name.to_s.singularize).to_s | ||
| assoc = through_association.klass.relations[source_name] || | ||
| raise( | ||
| Errors::InvalidRelationOption.new( | ||
| @owner_class, name, :source, source_name | ||
| ) | ||
| ) | ||
| if assoc.is_a?(Referenced::HasAndBelongsToMany) | ||
| raise( | ||
| Errors::InvalidRelationOption.new( | ||
| @owner_class, name, :source, | ||
| 'has_and_belongs_to_many is not supported as a :through source' | ||
| ) | ||
| ) | ||
| end | ||
| assoc | ||
| end | ||
| end | ||
|
|
||
| # Return a Criteria scoped to the target documents reachable from base | ||
| # via the through association. Performs two queries: one against the | ||
| # intermediate collection, one against the source collection. | ||
| # | ||
| # @param [ Document ] base The owner document. | ||
| # | ||
| # @return [ Mongoid::Criteria ] | ||
| def criteria(base) | ||
| through_crit = through_association.criteria(base) | ||
|
|
||
| crit = if source_association.stores_foreign_key? | ||
| # FK is on the intermediate (e.g. appointment.patient_id -> belongs_to :patient) | ||
| target_pk = source_association.primary_key # '_id' on Patient | ||
| source_fk = source_association.foreign_key # 'patient_id' on Appointment | ||
| source_association.klass.where( | ||
| target_pk => { '$in' => through_crit.pluck(source_fk) } | ||
| ) | ||
| else | ||
| # FK is on the source (e.g. reader.book_id -> has_many :readers on Book) | ||
| source_pk = source_association.primary_key # '_id' on intermediate (Book) | ||
| source_fk = source_association.foreign_key # 'book_id' on Reader | ||
| source_association.klass.where( | ||
| source_fk => { '$in' => through_crit.pluck(source_pk) } | ||
| ) | ||
| end | ||
| order ? crit.order_by(order) : crit | ||
| end | ||
|
jamis marked this conversation as resolved.
|
||
|
|
||
| # The default for validating the association object. | ||
| # | ||
| # @return [ false ] | ||
| def validation_default | ||
| false | ||
| end | ||
|
|
||
| private | ||
|
|
||
| def setup_instance_methods! | ||
| define_through_getter! | ||
| define_through_ids_getter! | ||
| define_readonly_setter! | ||
| define_existence_check! | ||
| self | ||
| end | ||
|
|
||
| def define_through_getter! | ||
| assoc = self | ||
| assoc_name = name | ||
| @owner_class.re_define_method(assoc_name) do |reload = false| | ||
| if reload || !instance_variable_defined?("@_#{assoc_name}") | ||
| set_relation(assoc_name, HasManyThrough::Proxy.new(self, assoc)) | ||
| end | ||
| instance_variable_get("@_#{assoc_name}") | ||
| end | ||
| end | ||
|
|
||
| def define_through_ids_getter! | ||
| assoc_name = name | ||
| ids_method = :"#{assoc_name.to_s.singularize}_ids" | ||
| @owner_class.re_define_method(ids_method) do | ||
| send(assoc_name).pluck(:_id) | ||
| end | ||
| end | ||
|
|
||
| def define_readonly_setter! | ||
| assoc = self | ||
| @owner_class.re_define_method(:"#{name}=") do |_object| | ||
| raise Mongoid::Errors::ReadonlyAssociation.new(self.class, assoc) | ||
| end | ||
| end | ||
|
|
||
| def default_primary_key | ||
| PRIMARY_KEY_DEFAULT | ||
| end | ||
| end | ||
| end | ||
| end | ||
| end | ||
99 changes: 99 additions & 0 deletions
99
lib/mongoid/association/referenced/has_many_through/eager.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| module Mongoid | ||
| module Association | ||
| module Referenced | ||
| class HasManyThrough | ||
| # Two-query eager preloader for has_many :through associations. | ||
| class Eager < Association::Eager | ||
| private | ||
|
|
||
| def preload | ||
| @docs.each { |d| set_relation(d, []) } | ||
|
|
||
| through_assoc = @association.through_association | ||
| source_assoc = @association.source_association | ||
|
|
||
| owner_pk = through_assoc.primary_key | ||
| through_fk = through_assoc.foreign_key | ||
|
|
||
| owner_ids = @docs.filter_map { |d| d.public_send(owner_pk) }.uniq | ||
| return if owner_ids.empty? | ||
|
|
||
| # Step 1: load all intermediate records | ||
| intermediates = through_assoc.klass | ||
| .where(through_fk => { '$in' => owner_ids }) | ||
| .to_a | ||
|
|
||
| # Step 2: map owner FK values to arrays of target docs | ||
| targets_by_owner_fk = build_targets_map(intermediates, through_fk, source_assoc) | ||
|
|
||
| # Step 3: set relation on each owner doc | ||
| @docs.each do |doc| | ||
| key_val = doc.public_send(owner_pk) | ||
| set_relation(doc, targets_by_owner_fk[key_val] || []) | ||
| end | ||
| end | ||
|
|
||
| # Build a Hash mapping each owner FK value to an array of target docs. | ||
| # Uses two different strategies depending on where the FK lives. | ||
| def build_targets_map(intermediates, through_fk, source_assoc) | ||
| if source_assoc.stores_foreign_key? | ||
| fk_on_intermediate_targets_map(intermediates, through_fk, source_assoc) | ||
| else | ||
| fk_on_source_targets_map(intermediates, through_fk, source_assoc) | ||
| end | ||
| end | ||
|
|
||
| # FK is on the intermediate (e.g. appointment.patient_id -> belongs_to :patient). | ||
| def fk_on_intermediate_targets_map(intermediates, through_fk, source_assoc) | ||
| source_fk_vals = intermediates.filter_map { |i| i.public_send(source_assoc.foreign_key) }.uniq | ||
| targets = source_assoc.klass.where( | ||
| source_assoc.primary_key => { '$in' => source_fk_vals } | ||
| ).to_a | ||
| targets_by_pk = targets.group_by { |t| t.public_send(source_assoc.primary_key) } | ||
|
|
||
| result = Hash.new { |h, k| h[k] = [] } | ||
| intermediates.each do |i| | ||
| owner_fk_val = i.public_send(through_fk) | ||
| matched = targets_by_pk[i.public_send(source_assoc.foreign_key)] || [] | ||
| result[owner_fk_val].concat(matched) | ||
| end | ||
| result | ||
| end | ||
|
|
||
| # FK is on the source (e.g. reader.book_id -> has_many :readers on Book). | ||
| def fk_on_source_targets_map(intermediates, through_fk, source_assoc) | ||
| source_pk = source_assoc.primary_key | ||
| intermediate_pks = intermediates.filter_map { |i| i.public_send(source_pk) }.uniq | ||
| targets = source_assoc.klass.where( | ||
| source_assoc.foreign_key => { '$in' => intermediate_pks } | ||
| ).to_a | ||
| targets_by_source_fk = targets.group_by { |t| t.public_send(source_assoc.foreign_key) } | ||
|
|
||
| result = Hash.new { |h, k| h[k] = [] } | ||
| intermediates.each do |i| | ||
| owner_fk_val = i.public_send(through_fk) | ||
| matched = targets_by_source_fk[i.public_send(source_pk)] || [] | ||
| result[owner_fk_val].concat(matched) | ||
| end | ||
|
jamis marked this conversation as resolved.
|
||
| result | ||
| end | ||
|
|
||
| def set_relation(doc, element) | ||
| return if doc.blank? | ||
|
|
||
| proxy = HasManyThrough::Proxy.new(doc, @association, preloaded: element) | ||
| doc.set_relation(@association.name, proxy) | ||
| end | ||
|
jamis marked this conversation as resolved.
|
||
|
|
||
| # Required by base class contract. Not called from preload since this | ||
| # class manages its own two-query traversal directly. | ||
| def group_by_key | ||
| @association.through_association.primary_key | ||
| end | ||
| end | ||
| end | ||
| end | ||
| end | ||
| end | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.