module Sequel::Model::Associations::DatasetMethods
Eager loading makes it so that you can load all associated records for a set of objects in a single query, instead of a separate query for each object.
Two separate implementations are provided. eager
should be used most of the time, as it loads associated records using one query per association. However, it does not allow you the ability to filter or order based on columns in associated tables. eager_graph
loads all records in a single query using JOINs, allowing you to filter or order based on columns in associated tables. However, eager_graph
is usually slower than eager
, especially if multiple one_to_many or many_to_many associations are joined.
You can cascade the eager loading (loading associations on associated objects) with no limit to the depth of the cascades. You do this by passing a hash to eager
or eager_graph
with the keys being associations of the current model and values being associations of the model associated with the current model via the key.
The arguments can be symbols or hashes with symbol keys (for cascaded eager loading). Examples:
Album.eager(:artist).all Album.eager_graph(:artist).all Album.eager(:artist, :genre).all Album.eager_graph(:artist, :genre).all Album.eager(:artist).eager(:genre).all Album.eager_graph(:artist).eager_graph(:genre).all Artist.eager(albums: :tracks).all Artist.eager_graph(albums: :tracks).all Artist.eager(albums: {tracks: :genre}).all Artist.eager_graph(albums: {tracks: :genre}).all
You can also pass a callback as a hash value in order to customize the dataset being eager loaded at query time, analogous to the way the :eager_block association option allows you to customize it at association definition time. For example, if you wanted artists with their albums since 1990:
Artist.eager(albums: proc{|ds| ds.where{year > 1990}})
Or if you needed albums and their artist's name only, using a single query:
Albums.eager_graph(artist: proc{|ds| ds.select(:name)})
To cascade eager loading while using a callback, you substitute the cascaded associations with a single entry hash that has the proc callback as the key and the cascaded associations as the value. This will load artists with their albums since 1990, and also the tracks on those albums and the genre for those tracks:
Artist.eager(albums: {proc{|ds| ds.where{year > 1990}}=>{tracks: :genre}})
Public Instance Methods
If the dataset is being eagerly loaded, default to calling all instead of each.
# File lib/sequel/model/associations.rb 3085 def as_hash(key_column=nil, value_column=nil, opts=OPTS) 3086 if (@opts[:eager_graph] || @opts[:eager]) && !opts.has_key?(:all) 3087 opts = Hash[opts] 3088 opts[:all] = true 3089 end 3090 super 3091 end
Adds one or more INNER JOINs to the existing dataset using the keys and conditions specified by the given association(s). Take the same arguments as eager_graph
, and operates similarly, but only adds the joins as opposed to making the other changes (such as adding selected columns and setting up eager loading).
The following methods also exist for specifying a different type of JOIN:
- association_full_join
-
FULL JOIN
- association_inner_join
-
INNER JOIN
- association_left_join
-
LEFT JOIN
- association_right_join
-
RIGHT JOIN
Examples:
# For each album, association_join load the artist Album.association_join(:artist).all # SELECT * # FROM albums # INNER JOIN artists AS artist ON (artists.id = albums.artist_id) # For each album, association_join load the artist, using a specified alias Album.association_join(Sequel[:artist].as(:a)).all # SELECT * # FROM albums # INNER JOIN artists AS a ON (a.id = albums.artist_id) # For each album, association_join load the artist and genre Album.association_join(:artist, :genre).all Album.association_join(:artist).association_join(:genre).all # SELECT * # FROM albums # INNER JOIN artists AS artist ON (artist.id = albums.artist_id) # INNER JOIN genres AS genre ON (genre.id = albums.genre_id) # For each artist, association_join load albums and tracks for each album Artist.association_join(albums: :tracks).all # SELECT * # FROM artists # INNER JOIN albums ON (albums.artist_id = artists.id) # INNER JOIN tracks ON (tracks.album_id = albums.id) # For each artist, association_join load albums, tracks for each album, and genre for each track Artist.association_join(albums: {tracks: :genre}).all # SELECT * # FROM artists # INNER JOIN albums ON (albums.artist_id = artists.id) # INNER JOIN tracks ON (tracks.album_id = albums.id) # INNER JOIN genres AS genre ON (genre.id = tracks.genre_id) # For each artist, association_join load albums with year > 1990 Artist.association_join(albums: proc{|ds| ds.where{year > 1990}}).all # SELECT * # FROM artists # INNER JOIN ( # SELECT * FROM albums WHERE (year > 1990) # ) AS albums ON (albums.artist_id = artists.id) # For each artist, association_join load albums and tracks 1-10 for each album Artist.association_join(albums: {tracks: proc{|ds| ds.where(number: 1..10)}}).all # SELECT * # FROM artists # INNER JOIN albums ON (albums.artist_id = artists.id) # INNER JOIN ( # SELECT * FROM tracks WHERE ((number >= 1) AND (number <= 10)) # ) AS tracks ON (tracks.albums_id = albums.id) # For each artist, association_join load albums with year > 1990, and tracks for those albums Artist.association_join(albums: {proc{|ds| ds.where{year > 1990}}=>:tracks}).all # SELECT * # FROM artists # INNER JOIN ( # SELECT * FROM albums WHERE (year > 1990) # ) AS albums ON (albums.artist_id = artists.id) # INNER JOIN tracks ON (tracks.album_id = albums.id)
# File lib/sequel/model/associations.rb 2805 def association_join(*associations) 2806 association_inner_join(*associations) 2807 end
If the expression is in the form x = y
where y
is a Sequel::Model
instance, array of Sequel::Model
instances, or a Sequel::Model
dataset, assume x
is an association symbol and look up the association reflection via the dataset's model. From there, return the appropriate SQL
based on the type of association and the values of the foreign/primary keys of y
. For most association types, this is a simple transformation, but for many_to_many
associations this creates a subquery to the join table.
# File lib/sequel/model/associations.rb 2816 def complex_expression_sql_append(sql, op, args) 2817 r = args[1] 2818 if (((op == :'=' || op == :'!=') && r.is_a?(Sequel::Model)) || 2819 (multiple = ((op == :IN || op == :'NOT IN') && ((is_ds = r.is_a?(Sequel::Dataset)) || (r.respond_to?(:all?) && r.all?{|x| x.is_a?(Sequel::Model)}))))) 2820 l = args[0] 2821 if ar = model.association_reflections[l] 2822 if multiple 2823 klass = ar.associated_class 2824 if is_ds 2825 if r.respond_to?(:model) 2826 unless r.model <= klass 2827 # A dataset for a different model class, could be a valid regular query 2828 return super 2829 end 2830 else 2831 # Not a model dataset, could be a valid regular query 2832 return super 2833 end 2834 else 2835 unless r.all?{|x| x.is_a?(klass)} 2836 raise Sequel::Error, "invalid association class for one object for association #{l.inspect} used in dataset filter for model #{model.inspect}, expected class #{klass.inspect}" 2837 end 2838 end 2839 elsif !r.is_a?(ar.associated_class) 2840 raise Sequel::Error, "invalid association class #{r.class.inspect} for association #{l.inspect} used in dataset filter for model #{model.inspect}, expected class #{ar.associated_class.inspect}" 2841 end 2842 2843 if exp = association_filter_expression(op, ar, r) 2844 literal_append(sql, exp) 2845 else 2846 raise Sequel::Error, "invalid association type #{ar[:type].inspect} for association #{l.inspect} used in dataset filter for model #{model.inspect}" 2847 end 2848 elsif multiple && (is_ds || r.empty?) 2849 # Not a query designed for this support, could be a valid regular query 2850 super 2851 else 2852 raise Sequel::Error, "invalid association #{l.inspect} used in dataset filter for model #{model.inspect}" 2853 end 2854 else 2855 super 2856 end 2857 end
The preferred eager loading method. Loads all associated records using one query for each association.
The basic idea for how it works is that the dataset is first loaded normally. Then it goes through all associations that have been specified via eager
. It loads each of those associations separately, then associates them back to the original dataset via primary/foreign keys. Due to the necessity of all objects being present, you need to use all
to use eager loading, as it can't work with each
.
This implementation avoids the complexity of extracting an object graph out of a single dataset, by building the object graph out of multiple datasets, one for each association. By using a separate dataset for each association, it avoids problems such as aliasing conflicts and creating cartesian product result sets if multiple one_to_many or many_to_many eager associations are requested.
One limitation of using this method is that you cannot filter the current dataset based on values of columns in an associated table, since the associations are loaded in separate queries. To do that you need to load all associations in the same query, and extract an object graph from the results of that query. If you need to filter based on columns in associated tables, look at eager_graph
or join the tables you need to filter on manually.
Each association's order, if defined, is respected. If the association uses a block or has an :eager_block argument, it is used.
To modify the associated dataset that will be used for the eager load, you should use a hash for the association, with the key being the association name symbol, and the value being a callable object that is called with the associated dataset and should return a modified dataset. If that association also has dependent associations, instead of a callable object, use a hash with the callable object being the key, and the dependent association(s) as the value.
Examples:
# For each album, eager load the artist Album.eager(:artist).all # SELECT * FROM albums # SELECT * FROM artists WHERE (id IN (...)) # For each album, eager load the artist and genre Album.eager(:artist, :genre).all Album.eager(:artist).eager(:genre).all # SELECT * FROM albums # SELECT * FROM artists WHERE (id IN (...)) # SELECT * FROM genres WHERE (id IN (...)) # For each artist, eager load albums and tracks for each album Artist.eager(albums: :tracks).all # SELECT * FROM artists # SELECT * FROM albums WHERE (artist_id IN (...)) # SELECT * FROM tracks WHERE (album_id IN (...)) # For each artist, eager load albums, tracks for each album, and genre for each track Artist.eager(albums: {tracks: :genre}).all # SELECT * FROM artists # SELECT * FROM albums WHERE (artist_id IN (...)) # SELECT * FROM tracks WHERE (album_id IN (...)) # SELECT * FROM genre WHERE (id IN (...)) # For each artist, eager load albums with year > 1990 Artist.eager(albums: proc{|ds| ds.where{year > 1990}}).all # SELECT * FROM artists # SELECT * FROM albums WHERE ((year > 1990) AND (artist_id IN (...))) # For each artist, eager load albums and tracks 1-10 for each album Artist.eager(albums: {tracks: proc{|ds| ds.where(number: 1..10)}}).all # SELECT * FROM artists # SELECT * FROM albums WHERE (artist_id IN (...)) # SELECT * FROM tracks WHERE ((number >= 1) AND (number <= 10) AND (album_id IN (...))) # For each artist, eager load albums with year > 1990, and tracks for those albums Artist.eager(albums: {proc{|ds| ds.where{year > 1990}}=>:tracks}).all # SELECT * FROM artists # SELECT * FROM albums WHERE ((year > 1990) AND (artist_id IN (...))) # SELECT * FROM albums WHERE (artist_id IN (...))
# File lib/sequel/model/associations.rb 2934 def eager(*associations) 2935 opts = @opts[:eager] 2936 association_opts = eager_options_for_associations(associations) 2937 opts = opts ? opts.merge(association_opts) : association_opts 2938 clone(:eager=>opts.freeze) 2939 end
The secondary eager loading method. Loads all associations in a single query. This method should only be used if you need to filter or order based on columns in associated tables, or if you have done comparative benchmarking it and determined it is faster.
This method uses Dataset#graph
to create appropriate aliases for columns in all the tables. Then it uses the graph's metadata to build the associations from the single hash, and finally replaces the array of hashes with an array model objects inside all.
Be very careful when using this with multiple one_to_many or many_to_many associations, as you can create large cartesian products. If you must graph multiple one_to_many and many_to_many associations, make sure your filters are narrow if the datasets are large.
Each association's order, if defined, is respected. eager_graph
probably won't work correctly on a limited dataset, unless you are only graphing many_to_one, one_to_one, and one_through_one associations.
Does not use the block defined for the association, since it does a single query for all objects. You can use the :graph_* association options to modify the SQL
query.
Like eager
, you need to call all
on the dataset for the eager loading to work. If you just call each
, it will yield plain hashes, each containing all columns from all the tables.
To modify the associated dataset that will be joined to the current dataset, you should use a hash for the association, with the key being the association name symbol, and the value being a callable object that is called with the associated dataset and should return a modified dataset. If that association also has dependent associations, instead of a callable object, use a hash with the callable object being the key, and the dependent association(s) as the value.
You can specify an alias by providing a Sequel::SQL::AliasedExpression
object instead of an a Symbol
for the assocation name.
Examples:
# For each album, eager_graph load the artist Album.eager_graph(:artist).all # SELECT ... # FROM albums # LEFT OUTER JOIN artists AS artist ON (artists.id = albums.artist_id) # For each album, eager_graph load the artist, using a specified alias Album.eager_graph(Sequel[:artist].as(:a)).all # SELECT ... # FROM albums # LEFT OUTER JOIN artists AS a ON (a.id = albums.artist_id) # For each album, eager_graph load the artist and genre Album.eager_graph(:artist, :genre).all Album.eager_graph(:artist).eager_graph(:genre).all # SELECT ... # FROM albums # LEFT OUTER JOIN artists AS artist ON (artist.id = albums.artist_id) # LEFT OUTER JOIN genres AS genre ON (genre.id = albums.genre_id) # For each artist, eager_graph load albums and tracks for each album Artist.eager_graph(albums: :tracks).all # SELECT ... # FROM artists # LEFT OUTER JOIN albums ON (albums.artist_id = artists.id) # LEFT OUTER JOIN tracks ON (tracks.album_id = albums.id) # For each artist, eager_graph load albums, tracks for each album, and genre for each track Artist.eager_graph(albums: {tracks: :genre}).all # SELECT ... # FROM artists # LEFT OUTER JOIN albums ON (albums.artist_id = artists.id) # LEFT OUTER JOIN tracks ON (tracks.album_id = albums.id) # LEFT OUTER JOIN genres AS genre ON (genre.id = tracks.genre_id) # For each artist, eager_graph load albums with year > 1990 Artist.eager_graph(albums: proc{|ds| ds.where{year > 1990}}).all # SELECT ... # FROM artists # LEFT OUTER JOIN ( # SELECT * FROM albums WHERE (year > 1990) # ) AS albums ON (albums.artist_id = artists.id) # For each artist, eager_graph load albums and tracks 1-10 for each album Artist.eager_graph(albums: {tracks: proc{|ds| ds.where(number: 1..10)}}).all # SELECT ... # FROM artists # LEFT OUTER JOIN albums ON (albums.artist_id = artists.id) # LEFT OUTER JOIN ( # SELECT * FROM tracks WHERE ((number >= 1) AND (number <= 10)) # ) AS tracks ON (tracks.albums_id = albums.id) # For each artist, eager_graph load albums with year > 1990, and tracks for those albums Artist.eager_graph(albums: {proc{|ds| ds.where{year > 1990}}=>:tracks}).all # SELECT ... # FROM artists # LEFT OUTER JOIN ( # SELECT * FROM albums WHERE (year > 1990) # ) AS albums ON (albums.artist_id = artists.id) # LEFT OUTER JOIN tracks ON (tracks.album_id = albums.id)
# File lib/sequel/model/associations.rb 3034 def eager_graph(*associations) 3035 eager_graph_with_options(associations) 3036 end
Run eager_graph
with some options specific to just this call. Unlike eager_graph
, this takes the associations as a single argument instead of multiple arguments.
Options:
- :join_type
-
Override the join type specified in the association
- :limit_strategy
-
Use a strategy for handling limits on associations. Appropriate :limit_strategy values are:
- true
-
Pick the most appropriate based on what the database supports
- :distinct_on
-
Force use of DISTINCT ON stategy (*_one associations only)
- :correlated_subquery
-
Force use of correlated subquery strategy (one_to_* associations only)
- :window_function
-
Force use of window function strategy
- :ruby
-
Don't modify the
SQL
, implement limits/offsets with array slicing
This can also be a hash with association name symbol keys and one of the above values, to use different strategies per association.
The default is the :ruby strategy. Choosing a different strategy can make your code significantly slower in some cases (perhaps even the majority of cases), so you should only use this if you have benchmarked that it is faster for your use cases.
# File lib/sequel/model/associations.rb 3058 def eager_graph_with_options(associations, opts=OPTS) 3059 opts = opts.dup unless opts.frozen? 3060 associations = [associations] unless associations.is_a?(Array) 3061 ds = if eg = @opts[:eager_graph] 3062 eg = eg.dup 3063 [:requirements, :reflections, :reciprocals, :limits].each{|k| eg[k] = eg[k].dup} 3064 eg[:local] = opts 3065 ds = clone(:eager_graph=>eg) 3066 ds.eager_graph_associations(ds, model, ds.opts[:eager_graph][:master], [], *associations) 3067 else 3068 # Each of the following have a symbol key for the table alias, with the following values: 3069 # :reciprocals :: the reciprocal value to use for this association 3070 # :reflections :: AssociationReflection instance related to this association 3071 # :requirements :: array of requirements for this association 3072 # :limits :: Any limit/offset array slicing that need to be handled in ruby land after loading 3073 opts = {:requirements=>{}, :master=>alias_symbol(first_source), :reflections=>{}, :reciprocals=>{}, :limits=>{}, :local=>opts, :cartesian_product_number=>0, :row_proc=>row_proc} 3074 ds = clone(:eager_graph=>opts) 3075 ds = ds.eager_graph_associations(ds, model, ds.opts[:eager_graph][:master], [], *associations).naked 3076 end 3077 3078 ds.opts[:eager_graph].freeze 3079 ds.opts[:eager_graph].each_value{|v| v.freeze if v.is_a?(Hash)} 3080 ds 3081 end
If the dataset is being eagerly loaded, default to calling all instead of each.
# File lib/sequel/model/associations.rb 3095 def to_hash_groups(key_column, value_column=nil, opts=OPTS) 3096 if (@opts[:eager_graph] || @opts[:eager]) && !opts.has_key?(:all) 3097 opts = Hash[opts] 3098 opts[:all] = true 3099 end 3100 super 3101 end
Do not attempt to split the result set into associations, just return results as simple objects. This is useful if you want to use eager_graph
as a shortcut to have all of the joins and aliasing set up, but want to do something else with the dataset.
# File lib/sequel/model/associations.rb 3107 def ungraphed 3108 ds = super.clone(:eager_graph=>nil) 3109 if (eg = @opts[:eager_graph]) && (rp = eg[:row_proc]) 3110 ds = ds.with_row_proc(rp) 3111 end 3112 ds 3113 end
Protected Instance Methods
Call graph on the association with the correct arguments, update the eager_graph
data structure, and recurse into eager_graph_associations
if there are any passed in associations (which would be dependencies of the current association)
Arguments:
- ds
-
Current dataset
- model
-
Current
Model
- ta
-
table_alias used for the parent association
- requirements
-
an array, used as a stack for requirements
- r
-
association reflection for the current association, or an
SQL::AliasedExpression
with the reflection as the expression and the alias base as the aliaz. - *associations
-
any associations dependent on this one
# File lib/sequel/model/associations.rb 3130 def eager_graph_association(ds, model, ta, requirements, r, *associations) 3131 if r.is_a?(SQL::AliasedExpression) 3132 alias_base = r.alias 3133 r = r.expression 3134 else 3135 alias_base = r[:graph_alias_base] 3136 end 3137 assoc_table_alias = ds.unused_table_alias(alias_base) 3138 loader = r[:eager_grapher] 3139 if !associations.empty? 3140 if associations.first.respond_to?(:call) 3141 callback = associations.first 3142 associations = {} 3143 elsif associations.length == 1 && (assocs = associations.first).is_a?(Hash) && assocs.length == 1 && (pr_assoc = assocs.to_a.first) && pr_assoc.first.respond_to?(:call) 3144 callback, assoc = pr_assoc 3145 associations = assoc.is_a?(Array) ? assoc : [assoc] 3146 end 3147 end 3148 local_opts = ds.opts[:eager_graph][:local] 3149 limit_strategy = r.eager_graph_limit_strategy(local_opts[:limit_strategy]) 3150 3151 if r[:conditions] && !Sequel.condition_specifier?(r[:conditions]) && !r[:orig_opts].has_key?(:graph_conditions) && !r[:orig_opts].has_key?(:graph_only_conditions) && !r.has_key?(:graph_block) 3152 raise Error, "Cannot eager_graph association when :conditions specified and not a hash or an array of pairs. Specify :graph_conditions, :graph_only_conditions, or :graph_block for the association. Model: #{r[:model]}, association: #{r[:name]}" 3153 end 3154 3155 ds = loader.call(:self=>ds, :table_alias=>assoc_table_alias, :implicit_qualifier=>(ta == ds.opts[:eager_graph][:master]) ? first_source : qualifier_from_alias_symbol(ta, first_source), :callback=>callback, :join_type=>local_opts[:join_type], :join_only=>local_opts[:join_only], :limit_strategy=>limit_strategy, :from_self_alias=>ds.opts[:eager_graph][:master]) 3156 if r[:order_eager_graph] && (order = r.fetch(:graph_order, r[:order])) 3157 ds = ds.order_append(*qualified_expression(order, assoc_table_alias)) 3158 end 3159 eager_graph = ds.opts[:eager_graph] 3160 eager_graph[:requirements][assoc_table_alias] = requirements.dup 3161 eager_graph[:reflections][assoc_table_alias] = r 3162 if limit_strategy == :ruby 3163 eager_graph[:limits][assoc_table_alias] = r.limit_and_offset 3164 end 3165 eager_graph[:cartesian_product_number] += r[:cartesian_product_number] || 2 3166 ds = ds.eager_graph_associations(ds, r.associated_class, assoc_table_alias, requirements + [assoc_table_alias], *associations) unless associations.empty? 3167 ds 3168 end
Check the associations are valid for the given model. Call eager_graph_association
on each association.
Arguments:
- ds
-
Current dataset
- model
-
Current
Model
- ta
-
table_alias used for the parent association
- requirements
-
an array, used as a stack for requirements
- *associations
-
the associations to add to the graph
# File lib/sequel/model/associations.rb 3179 def eager_graph_associations(ds, model, ta, requirements, *associations) 3180 return ds if associations.empty? 3181 associations.flatten.each do |association| 3182 ds = case association 3183 when Symbol, SQL::AliasedExpression 3184 ds.eager_graph_association(ds, model, ta, requirements, eager_graph_check_association(model, association)) 3185 when Hash 3186 association.each do |assoc, assoc_assocs| 3187 ds = ds.eager_graph_association(ds, model, ta, requirements, eager_graph_check_association(model, assoc), assoc_assocs) 3188 end 3189 ds 3190 else 3191 raise(Sequel::Error, 'Associations must be in the form of a symbol or hash') 3192 end 3193 end 3194 ds 3195 end
Replace the array of plain hashes with an array of model objects will all eager_graphed associations set in the associations cache for each object.
# File lib/sequel/model/associations.rb 3199 def eager_graph_build_associations(hashes) 3200 hashes.replace(_eager_graph_build_associations(hashes, eager_graph_loader)) 3201 end
Private Instance Methods
Return a new dataset with JOINs of the given type added, using the tables and conditions specified by the associations.
# File lib/sequel/model/associations.rb 3207 def _association_join(type, associations) 3208 clone(:join=>clone(:graph_from_self=>false).eager_graph_with_options(associations, :join_type=>type, :join_only=>true).opts[:join]) 3209 end
Process the array of hashes using the eager graph loader to return an array of model objects with the associations set.
# File lib/sequel/model/associations.rb 3213 def _eager_graph_build_associations(hashes, egl) 3214 egl.load(hashes) 3215 end
If the association has conditions itself, then it requires additional filters be added to the current dataset to ensure that the passed in object would also be included by the association's conditions.
# File lib/sequel/model/associations.rb 3220 def add_association_filter_conditions(ref, obj, expr) 3221 if expr != SQL::Constants::FALSE && ref.filter_by_associations_add_conditions? 3222 Sequel[ref.filter_by_associations_conditions_expression(obj)] 3223 else 3224 expr 3225 end 3226 end
Return an expression for filtering by the given association reflection and associated object.
# File lib/sequel/model/associations.rb 3248 def association_filter_expression(op, ref, obj) 3249 meth = :"#{ref[:type]}_association_filter_expression" 3250 # Allow calling private association specific method to get filter expression 3251 send(meth, op, ref, obj) if respond_to?(meth, true) 3252 end
Handle inversion for association filters by returning an inverted expression, plus also handling cases where the referenced columns are NULL.
# File lib/sequel/model/associations.rb 3256 def association_filter_handle_inversion(op, exp, cols) 3257 if op == :'!=' || op == :'NOT IN' 3258 if exp == SQL::Constants::FALSE 3259 ~exp 3260 else 3261 ~exp | Sequel::SQL::BooleanExpression.from_value_pairs(cols.zip([]), :OR) 3262 end 3263 else 3264 exp 3265 end 3266 end
Return an expression for making sure that the given keys match the value of the given methods for either the single object given or for any of the objects given if obj
is an array.
# File lib/sequel/model/associations.rb 3271 def association_filter_key_expression(keys, meths, obj) 3272 vals = if obj.is_a?(Sequel::Dataset) 3273 {(keys.length == 1 ? keys.first : keys)=>obj.select(*meths).exclude(Sequel::SQL::BooleanExpression.from_value_pairs(meths.zip([]), :OR))} 3274 else 3275 vals = Array(obj).reject{|o| !meths.all?{|m| o.get_column_value(m)}} 3276 return SQL::Constants::FALSE if vals.empty? 3277 if obj.is_a?(Array) 3278 if keys.length == 1 3279 meth = meths.first 3280 {keys.first=>vals.map{|o| o.get_column_value(meth)}} 3281 else 3282 {keys=>vals.map{|o| meths.map{|m| o.get_column_value(m)}}} 3283 end 3284 else 3285 keys.zip(meths.map{|k| obj.get_column_value(k)}) 3286 end 3287 end 3288 SQL::BooleanExpression.from_value_pairs(vals) 3289 end
Make sure the association is valid for this model, and return the related AssociationReflection
.
# File lib/sequel/model/associations.rb 3292 def check_association(model, association) 3293 raise(Sequel::UndefinedAssociation, "Invalid association #{association} for #{model.name}") unless reflection = model.association_reflection(association) 3294 raise(Sequel::Error, "Eager loading is not allowed for #{model.name} association #{association}") if reflection[:allow_eager] == false 3295 reflection 3296 end
Allow associations that are eagerly graphed to be specified as an SQL::AliasedExpression
, for per-call determining of the alias base.
# File lib/sequel/model/associations.rb 3300 def eager_graph_check_association(model, association) 3301 if association.is_a?(SQL::AliasedExpression) 3302 expr = association.expression 3303 if expr.is_a?(SQL::Identifier) 3304 expr = expr.value 3305 if expr.is_a?(String) 3306 expr = expr.to_sym 3307 end 3308 end 3309 3310 SQL::AliasedExpression.new(check_association(model, expr), association.alias) 3311 else 3312 check_association(model, association) 3313 end 3314 end
The EagerGraphLoader
instance used for converting eager_graph
results.
# File lib/sequel/model/associations.rb 3317 def eager_graph_loader 3318 unless egl = cache_get(:_model_eager_graph_loader) 3319 egl = cache_set(:_model_eager_graph_loader, EagerGraphLoader.new(self)) 3320 end 3321 egl.dup 3322 end
Eagerly load all specified associations
# File lib/sequel/model/associations.rb 3325 def eager_load(a, eager_assoc=@opts[:eager]) 3326 return if a.empty? 3327 # Key is foreign/primary key name symbol. 3328 # Value is hash with keys being foreign/primary key values (generally integers) 3329 # and values being an array of current model objects with that specific foreign/primary key 3330 key_hash = {} 3331 # Reflections for all associations to eager load 3332 reflections = eager_assoc.keys.map{|assoc| model.association_reflection(assoc) || (raise Sequel::UndefinedAssociation, "Model: #{self}, Association: #{assoc}")} 3333 3334 # Populate the key_hash entry for each association being eagerly loaded 3335 reflections.each do |r| 3336 if key = r.eager_loader_key 3337 # key_hash for this key has already been populated, 3338 # skip populating again so that duplicate values 3339 # aren't added. 3340 unless id_map = key_hash[key] 3341 id_map = key_hash[key] = Hash.new{|h,k| h[k] = []} 3342 3343 # Supporting both single (Symbol) and composite (Array) keys. 3344 a.each do |rec| 3345 case key 3346 when Array 3347 if (k = key.map{|k2| rec.get_column_value(k2)}) && k.all? 3348 id_map[k] << rec 3349 end 3350 when Symbol 3351 if k = rec.get_column_value(key) 3352 id_map[k] << rec 3353 end 3354 else 3355 raise Error, "unhandled eager_loader_key #{key.inspect} for association #{r[:name]}" 3356 end 3357 end 3358 end 3359 else 3360 id_map = nil 3361 end 3362 3363 loader = r[:eager_loader] 3364 associations = eager_assoc[r[:name]] 3365 if associations.respond_to?(:call) 3366 eager_block = associations 3367 associations = OPTS 3368 elsif associations.is_a?(Hash) && associations.length == 1 && (pr_assoc = associations.to_a.first) && pr_assoc.first.respond_to?(:call) 3369 eager_block, associations = pr_assoc 3370 end 3371 loader.call(:key_hash=>key_hash, :rows=>a, :associations=>associations, :self=>self, :eager_block=>eager_block, :id_map=>id_map) 3372 a.each{|object| object.send(:run_association_callbacks, r, :after_load, object.associations[r[:name]])} if r[:after_load] 3373 end 3374 end
Process the array of associations arguments (Symbols, Arrays, and Hashes), and return a hash of options suitable for cascading.
# File lib/sequel/model/associations.rb 3230 def eager_options_for_associations(associations) 3231 opts = {} 3232 associations.flatten.each do |association| 3233 case association 3234 when Symbol 3235 check_association(model, association) 3236 opts[association] = nil 3237 when Hash 3238 association.keys.each{|assoc| check_association(model, assoc)} 3239 opts.merge!(association) 3240 else 3241 raise(Sequel::Error, 'Associations must be in the form of a symbol or hash') 3242 end 3243 end 3244 opts 3245 end
Return a subquery expression for filering by a many_to_many association
# File lib/sequel/model/associations.rb 3377 def many_to_many_association_filter_expression(op, ref, obj) 3378 lpks, lks, rks = ref.values_at(:left_primary_key_columns, :left_keys, :right_keys) 3379 jt = ref.join_table_alias 3380 lpks = lpks.first if lpks.length == 1 3381 lpks = ref.qualify(model.table_name, lpks) 3382 3383 meths = if obj.is_a?(Sequel::Dataset) 3384 ref.qualify(obj.model.table_name, ref.right_primary_keys) 3385 else 3386 ref.right_primary_key_methods 3387 end 3388 3389 expr = association_filter_key_expression(ref.qualify(jt, rks), meths, obj) 3390 unless expr == SQL::Constants::FALSE 3391 expr = SQL::BooleanExpression.from_value_pairs(lpks=>model.db.from(ref[:join_table]).select(*ref.qualify(jt, lks)).where(expr).exclude(SQL::BooleanExpression.from_value_pairs(ref.qualify(jt, lks).zip([]), :OR))) 3392 expr = add_association_filter_conditions(ref, obj, expr) 3393 end 3394 3395 association_filter_handle_inversion(op, expr, Array(lpks)) 3396 end
Return a simple equality expression for filering by a many_to_one association
# File lib/sequel/model/associations.rb 3400 def many_to_one_association_filter_expression(op, ref, obj) 3401 keys = ref.qualify(model.table_name, ref[:key_columns]) 3402 meths = if obj.is_a?(Sequel::Dataset) 3403 ref.qualify(obj.model.table_name, ref.primary_keys) 3404 else 3405 ref.primary_key_methods 3406 end 3407 3408 expr = association_filter_key_expression(keys, meths, obj) 3409 expr = add_association_filter_conditions(ref, obj, expr) 3410 association_filter_handle_inversion(op, expr, keys) 3411 end
# File lib/sequel/model/associations.rb 3428 def non_sql_option?(key) 3429 super || key == :eager || key == :eager_graph 3430 end
Return a simple equality expression for filering by a one_to_* association
# File lib/sequel/model/associations.rb 3414 def one_to_many_association_filter_expression(op, ref, obj) 3415 keys = ref.qualify(model.table_name, ref[:primary_key_columns]) 3416 meths = if obj.is_a?(Sequel::Dataset) 3417 ref.qualify(obj.model.table_name, ref[:keys]) 3418 else 3419 ref[:key_methods] 3420 end 3421 3422 expr = association_filter_key_expression(keys, meths, obj) 3423 expr = add_association_filter_conditions(ref, obj, expr) 3424 association_filter_handle_inversion(op, expr, keys) 3425 end
Build associations from the graph if eager_graph
was used, and/or load other associations if eager
was used.
# File lib/sequel/model/associations.rb 3434 def post_load(all_records) 3435 eager_graph_build_associations(all_records) if @opts[:eager_graph] 3436 eager_load(all_records) if @opts[:eager] && (row_proc || @opts[:eager_graph]) 3437 super 3438 end