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
Source
# File lib/sequel/model/associations.rb 3336 def as_hash(key_column=nil, value_column=nil, opts=OPTS) 3337 if (@opts[:eager_graph] || @opts[:eager]) && !opts.has_key?(:all) 3338 opts = Hash[opts] 3339 opts[:all] = true 3340 end 3341 super 3342 end
If the dataset is being eagerly loaded, default to calling all instead of each.
Source
# File lib/sequel/model/associations.rb 3042 def association_join(*associations) 3043 association_inner_join(*associations) 3044 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)
Source
# File lib/sequel/model/associations.rb 3053 def complex_expression_sql_append(sql, op, args) 3054 r = args[1] 3055 if (((op == :'=' || op == :'!=') && r.is_a?(Sequel::Model)) || 3056 (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)}))))) 3057 l = args[0] 3058 if ar = model.association_reflections[l] 3059 raise Error, "filtering by associations is not allowed for #{ar.inspect}" if ar[:allow_filtering_by] == false 3060 3061 if multiple 3062 klass = ar.associated_class 3063 if is_ds 3064 if r.respond_to?(:model) 3065 unless r.model <= klass 3066 # A dataset for a different model class, could be a valid regular query 3067 return super 3068 end 3069 else 3070 # Not a model dataset, could be a valid regular query 3071 return super 3072 end 3073 else 3074 unless r.all?{|x| x.is_a?(klass)} 3075 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}" 3076 end 3077 end 3078 elsif !r.is_a?(ar.associated_class) 3079 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}" 3080 end 3081 3082 if exp = association_filter_expression(op, ar, r) 3083 literal_append(sql, exp) 3084 else 3085 raise Sequel::Error, "invalid association type #{ar[:type].inspect} for association #{l.inspect} used in dataset filter for model #{model.inspect}" 3086 end 3087 elsif multiple && (is_ds || r.empty?) 3088 # Not a query designed for this support, could be a valid regular query 3089 super 3090 else 3091 raise Sequel::Error, "invalid association #{l.inspect} used in dataset filter for model #{model.inspect}" 3092 end 3093 else 3094 super 3095 end 3096 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.
Source
# File lib/sequel/model/associations.rb 3173 def eager(*associations) 3174 opts = @opts[:eager] 3175 association_opts = eager_options_for_associations(associations) 3176 opts = opts ? opts.merge(association_opts) : association_opts 3177 clone(:eager=>opts.freeze) 3178 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 (...))
Source
# File lib/sequel/model/associations.rb 3283 def eager_graph(*associations) 3284 eager_graph_with_options(associations) 3285 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 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 custom alias and/or join type on a per-association basis by providing an Sequel::SQL::AliasedExpression
object instead of an a Symbol
for the association name.
You cannot mix calls to eager_graph
and graph
on the same dataset.
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, using a specified alias # and custom join type Album.eager_graph(Sequel[:artist].as(:a, join_type: :inner)).all # SELECT ... # FROM albums # INNER 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)
Source
# File lib/sequel/model/associations.rb 3307 def eager_graph_with_options(associations, opts=OPTS) 3308 return self if associations.empty? 3309 3310 opts = opts.dup unless opts.frozen? 3311 associations = [associations] unless associations.is_a?(Array) 3312 ds = if eg = @opts[:eager_graph] 3313 eg = eg.dup 3314 [:requirements, :reflections, :reciprocals, :limits].each{|k| eg[k] = eg[k].dup} 3315 eg[:local] = opts 3316 ds = clone(:eager_graph=>eg) 3317 ds.eager_graph_associations(ds, model, ds.opts[:eager_graph][:master], [], *associations) 3318 else 3319 # Each of the following have a symbol key for the table alias, with the following values: 3320 # :reciprocals :: the reciprocal value to use for this association 3321 # :reflections :: AssociationReflection instance related to this association 3322 # :requirements :: array of requirements for this association 3323 # :limits :: Any limit/offset array slicing that need to be handled in ruby land after loading 3324 opts = {:requirements=>{}, :master=>alias_symbol(first_source), :reflections=>{}, :reciprocals=>{}, :limits=>{}, :local=>opts, :cartesian_product_number=>0, :row_proc=>row_proc} 3325 ds = clone(:eager_graph=>opts) 3326 ds = ds.eager_graph_associations(ds, model, ds.opts[:eager_graph][:master], [], *associations).naked 3327 end 3328 3329 ds.opts[:eager_graph].freeze 3330 ds.opts[:eager_graph].each_value{|v| v.freeze if v.is_a?(Hash)} 3331 ds 3332 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.
Source
# File lib/sequel/model/associations.rb 3346 def to_hash_groups(key_column, value_column=nil, opts=OPTS) 3347 if (@opts[:eager_graph] || @opts[:eager]) && !opts.has_key?(:all) 3348 opts = Hash[opts] 3349 opts[:all] = true 3350 end 3351 super 3352 end
If the dataset is being eagerly loaded, default to calling all instead of each.
Source
# File lib/sequel/model/associations.rb 3358 def ungraphed 3359 ds = super.clone(:eager_graph=>nil) 3360 if (eg = @opts[:eager_graph]) && (rp = eg[:row_proc]) 3361 ds = ds.with_row_proc(rp) 3362 end 3363 ds 3364 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.
Protected Instance Methods
Source
# File lib/sequel/model/associations.rb 3383 def eager_graph_association(ds, model, ta, requirements, r, *associations) 3384 if r.is_a?(SQL::AliasedExpression) 3385 alias_base = r.alias 3386 if r.columns.is_a?(Hash) 3387 join_type = r.columns[:join_type] 3388 end 3389 r = r.expression 3390 else 3391 alias_base = r[:graph_alias_base] 3392 end 3393 assoc_table_alias = ds.unused_table_alias(alias_base) 3394 loader = r[:eager_grapher] 3395 if !associations.empty? 3396 if associations.first.respond_to?(:call) 3397 callback = associations.first 3398 associations = {} 3399 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) 3400 callback, assoc = pr_assoc 3401 associations = assoc.is_a?(Array) ? assoc : [assoc] 3402 end 3403 end 3404 local_opts = ds.opts[:eager_graph][:local] 3405 limit_strategy = r.eager_graph_limit_strategy(local_opts[:limit_strategy]) 3406 3407 # SEQUEL6: remove and integrate the auto_restrict_eager_graph plugin 3408 if !r[:orig_opts].has_key?(:graph_conditions) && !r[:orig_opts].has_key?(:graph_only_conditions) && !r.has_key?(:graph_block) && !r[:allow_eager_graph] 3409 if r[:conditions] && !Sequel.condition_specifier?(r[:conditions]) 3410 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]}" 3411 end 3412 3413 if r[:block] && !r[:graph_use_association_block] 3414 warn "eager_graph used for association when association given a block without graph options. The block is ignored in this case. This will result in an exception starting in Sequel 6. Model: #{r[:model]}, association: #{r[:name]}" 3415 end 3416 end 3417 3418 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=>join_type || local_opts[:join_type], :join_only=>local_opts[:join_only], :limit_strategy=>limit_strategy, :from_self_alias=>ds.opts[:eager_graph][:master]) 3419 if r[:order_eager_graph] && (order = r.fetch(:graph_order, r[:order])) 3420 ds = ds.order_append(*qualified_expression(order, assoc_table_alias)) 3421 end 3422 eager_graph = ds.opts[:eager_graph] 3423 eager_graph[:requirements][assoc_table_alias] = requirements.dup 3424 eager_graph[:reflections][assoc_table_alias] = r 3425 if limit_strategy == :ruby 3426 eager_graph[:limits][assoc_table_alias] = r.limit_and_offset 3427 end 3428 eager_graph[:cartesian_product_number] += r[:cartesian_product_number] || 2 3429 ds = ds.eager_graph_associations(ds, r.associated_class, assoc_table_alias, requirements + [assoc_table_alias], *associations) unless associations.empty? 3430 ds 3431 end
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, the alias base as the alias (or nil to use the default alias), and an optional hash with a :join_type entry as the columns to use a custom join type. - *associations
-
any associations dependent on this one
Source
# File lib/sequel/model/associations.rb 3442 def eager_graph_associations(ds, model, ta, requirements, *associations) 3443 associations.flatten.each do |association| 3444 ds = case association 3445 when Symbol, SQL::AliasedExpression 3446 ds.eager_graph_association(ds, model, ta, requirements, eager_graph_check_association(model, association)) 3447 when Hash 3448 association.each do |assoc, assoc_assocs| 3449 ds = ds.eager_graph_association(ds, model, ta, requirements, eager_graph_check_association(model, assoc), assoc_assocs) 3450 end 3451 ds 3452 else 3453 raise(Sequel::Error, 'Associations must be in the form of a symbol or hash') 3454 end 3455 end 3456 ds 3457 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
Source
# File lib/sequel/model/associations.rb 3461 def eager_graph_build_associations(hashes) 3462 hashes.replace(_eager_graph_build_associations(hashes, eager_graph_loader)) 3463 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.
Private Instance Methods
Source
# File lib/sequel/model/associations.rb 3469 def _association_join(type, associations) 3470 clone(:join=>clone(:graph_from_self=>false).eager_graph_with_options(associations, :join_type=>type, :join_only=>true).opts[:join]) 3471 end
Return a new dataset with JOINs of the given type added, using the tables and conditions specified by the associations.
Source
# File lib/sequel/model/associations.rb 3475 def _eager_graph_build_associations(hashes, egl) 3476 egl.load(hashes) 3477 end
Process the array of hashes using the eager graph loader to return an array of model objects with the associations set.
Source
# File lib/sequel/model/associations.rb 3482 def add_association_filter_conditions(ref, obj, expr) 3483 if expr != SQL::Constants::FALSE && ref.filter_by_associations_add_conditions? 3484 Sequel[ref.filter_by_associations_conditions_expression(obj)] 3485 else 3486 expr 3487 end 3488 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.
Source
# File lib/sequel/model/associations.rb 3510 def association_filter_expression(op, ref, obj) 3511 meth = :"#{ref[:type]}_association_filter_expression" 3512 # Allow calling private association specific method to get filter expression 3513 send(meth, op, ref, obj) if respond_to?(meth, true) 3514 end
Return an expression for filtering by the given association reflection and associated object.
Source
# File lib/sequel/model/associations.rb 3518 def association_filter_handle_inversion(op, exp, cols) 3519 if op == :'!=' || op == :'NOT IN' 3520 if exp == SQL::Constants::FALSE 3521 ~exp 3522 else 3523 ~exp | Sequel::SQL::BooleanExpression.from_value_pairs(cols.zip([]), :OR) 3524 end 3525 else 3526 exp 3527 end 3528 end
Handle inversion for association filters by returning an inverted expression, plus also handling cases where the referenced columns are NULL.
Source
# File lib/sequel/model/associations.rb 3533 def association_filter_key_expression(keys, meths, obj) 3534 vals = if obj.is_a?(Sequel::Dataset) 3535 {(keys.length == 1 ? keys.first : keys)=>obj.select(*meths).exclude(Sequel::SQL::BooleanExpression.from_value_pairs(meths.zip([]), :OR))} 3536 else 3537 vals = Array(obj).reject{|o| !meths.all?{|m| o.get_column_value(m)}} 3538 return SQL::Constants::FALSE if vals.empty? 3539 if obj.is_a?(Array) 3540 if keys.length == 1 3541 meth = meths.first 3542 {keys.first=>vals.map{|o| o.get_column_value(meth)}} 3543 else 3544 {keys=>vals.map{|o| meths.map{|m| o.get_column_value(m)}}} 3545 end 3546 else 3547 keys.zip(meths.map{|k| obj.get_column_value(k)}) 3548 end 3549 end 3550 SQL::BooleanExpression.from_value_pairs(vals) 3551 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.
Source
# File lib/sequel/model/associations.rb 3554 def check_association(model, association) 3555 raise(Sequel::UndefinedAssociation, "Invalid association #{association} for #{model.name}") unless reflection = model.association_reflection(association) 3556 raise(Sequel::Error, "Eager loading is not allowed for #{model.name} association #{association}") if reflection[:allow_eager] == false 3557 reflection 3558 end
Make sure the association is valid for this model, and return the related AssociationReflection
.
Source
# File lib/sequel/model/associations.rb 3562 def eager_graph_check_association(model, association) 3563 reflection = if association.is_a?(SQL::AliasedExpression) 3564 expr = association.expression 3565 if expr.is_a?(SQL::Identifier) 3566 expr = expr.value 3567 if expr.is_a?(String) 3568 expr = expr.to_sym 3569 end 3570 end 3571 3572 check_reflection = check_association(model, expr) 3573 SQL::AliasedExpression.new(check_reflection, association.alias || expr, association.columns) 3574 else 3575 check_reflection = check_association(model, association) 3576 end 3577 3578 if check_reflection && check_reflection[:allow_eager_graph] == false 3579 raise Error, "eager_graph not allowed for #{reflection.inspect}" 3580 end 3581 3582 reflection 3583 end
Allow associations that are eagerly graphed to be specified as an SQL::AliasedExpression
, for per-call determining of the alias base.
Source
# File lib/sequel/model/associations.rb 3586 def eager_graph_loader 3587 unless egl = cache_get(:_model_eager_graph_loader) 3588 egl = cache_set(:_model_eager_graph_loader, EagerGraphLoader.new(self)) 3589 end 3590 egl.dup 3591 end
The EagerGraphLoader
instance used for converting eager_graph
results.
Source
# File lib/sequel/model/associations.rb 3594 def eager_load(a, eager_assoc=@opts[:eager], m=model) 3595 return if a.empty? 3596 3597 # Reflections for all associations to eager load 3598 reflections = eager_assoc.keys.map{|assoc| m.association_reflection(assoc) || (raise Sequel::UndefinedAssociation, "Model: #{self}, Association: #{assoc}")} 3599 3600 perform_eager_loads(prepare_eager_load(a, reflections, eager_assoc)) 3601 3602 reflections.each do |r| 3603 a.each{|object| object.send(:run_association_callbacks, r, :after_load, object.associations[r[:name]])} if r[:after_load] 3604 end 3605 3606 nil 3607 end
Eagerly load all specified associations.
Source
# File lib/sequel/model/associations.rb 3492 def eager_options_for_associations(associations) 3493 opts = {} 3494 associations.flatten.each do |association| 3495 case association 3496 when Symbol 3497 check_association(model, association) 3498 opts[association] = nil 3499 when Hash 3500 association.keys.each{|assoc| check_association(model, assoc)} 3501 opts.merge!(association) 3502 else 3503 raise(Sequel::Error, 'Associations must be in the form of a symbol or hash') 3504 end 3505 end 3506 opts 3507 end
Process the array of associations arguments (Symbols, Arrays, and Hashes), and return a hash of options suitable for cascading.
Source
# File lib/sequel/model/associations.rb 3674 def many_to_many_association_filter_expression(op, ref, obj) 3675 lpks, lks, rks = ref.values_at(:left_primary_key_columns, :left_keys, :right_keys) 3676 jt = ref.join_table_alias 3677 lpks = lpks.first if lpks.length == 1 3678 lpks = ref.qualify(model.table_name, lpks) 3679 3680 meths = if obj.is_a?(Sequel::Dataset) 3681 ref.qualify(obj.model.table_name, ref.right_primary_keys) 3682 else 3683 ref.right_primary_key_methods 3684 end 3685 3686 expr = association_filter_key_expression(ref.qualify(jt, rks), meths, obj) 3687 unless expr == SQL::Constants::FALSE 3688 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))) 3689 expr = add_association_filter_conditions(ref, obj, expr) 3690 end 3691 3692 association_filter_handle_inversion(op, expr, Array(lpks)) 3693 end
Return a subquery expression for filering by a many_to_many association
Source
# File lib/sequel/model/associations.rb 3697 def many_to_one_association_filter_expression(op, ref, obj) 3698 keys = ref.qualify(model.table_name, ref[:key_columns]) 3699 meths = if obj.is_a?(Sequel::Dataset) 3700 ref.qualify(obj.model.table_name, ref.primary_keys) 3701 else 3702 ref.primary_key_methods 3703 end 3704 3705 expr = association_filter_key_expression(keys, meths, obj) 3706 expr = add_association_filter_conditions(ref, obj, expr) 3707 association_filter_handle_inversion(op, expr, keys) 3708 end
Return a simple equality expression for filering by a many_to_one association
Source
# File lib/sequel/model/associations.rb 3725 def non_sql_option?(key) 3726 super || key == :eager || key == :eager_graph 3727 end
Source
# File lib/sequel/model/associations.rb 3711 def one_to_many_association_filter_expression(op, ref, obj) 3712 keys = ref.qualify(model.table_name, ref[:primary_key_columns]) 3713 meths = if obj.is_a?(Sequel::Dataset) 3714 ref.qualify(obj.model.table_name, ref[:keys]) 3715 else 3716 ref[:key_methods] 3717 end 3718 3719 expr = association_filter_key_expression(keys, meths, obj) 3720 expr = add_association_filter_conditions(ref, obj, expr) 3721 association_filter_handle_inversion(op, expr, keys) 3722 end
Return a simple equality expression for filering by a one_to_* association
Source
# File lib/sequel/model/associations.rb 3669 def perform_eager_load(loader, eo) 3670 loader.call(eo) 3671 end
Perform eager loading for a single association using the loader and eager options.
Source
# File lib/sequel/model/associations.rb 3662 def perform_eager_loads(eager_load_data) 3663 eager_load_data.map do |loader, eo| 3664 perform_eager_load(loader, eo) 3665 end 3666 end
Using the hash of loaders and eager options, perform the eager loading.
Source
# File lib/sequel/model/associations.rb 3731 def post_load(all_records) 3732 eager_graph_build_associations(all_records) if @opts[:eager_graph] 3733 eager_load(all_records) if @opts[:eager] && (row_proc || @opts[:eager_graph]) 3734 super 3735 end
Build associations from the graph if eager_graph
was used, and/or load other associations if eager
was used.
Source
# File lib/sequel/model/associations.rb 3610 def prepare_eager_load(a, reflections, eager_assoc) 3611 eager_load_data = {} 3612 3613 # Key is foreign/primary key name symbol. 3614 # Value is hash with keys being foreign/primary key values (generally integers) 3615 # and values being an array of current model objects with that specific foreign/primary key 3616 key_hash = {} 3617 3618 # Populate the key_hash entry for each association being eagerly loaded 3619 reflections.each do |r| 3620 if key = r.eager_loader_key 3621 # key_hash for this key has already been populated, 3622 # skip populating again so that duplicate values 3623 # aren't added. 3624 unless id_map = key_hash[key] 3625 id_map = key_hash[key] = Hash.new{|h,k| h[k] = []} 3626 3627 # Supporting both single (Symbol) and composite (Array) keys. 3628 a.each do |rec| 3629 case key 3630 when Array 3631 if (k = key.map{|k2| rec.get_column_value(k2)}) && k.all? 3632 id_map[k] << rec 3633 end 3634 when Symbol 3635 if k = rec.get_column_value(key) 3636 id_map[k] << rec 3637 end 3638 else 3639 raise Error, "unhandled eager_loader_key #{key.inspect} for association #{r[:name]}" 3640 end 3641 end 3642 end 3643 else 3644 id_map = nil 3645 end 3646 3647 associations = eager_assoc[r[:name]] 3648 if associations.respond_to?(:call) 3649 eager_block = associations 3650 associations = OPTS 3651 elsif associations.is_a?(Hash) && associations.length == 1 && (pr_assoc = associations.to_a.first) && pr_assoc.first.respond_to?(:call) 3652 eager_block, associations = pr_assoc 3653 end 3654 3655 eager_load_data[r[:eager_loader]] = {:key_hash=>key_hash, :rows=>a, :associations=>associations, :self=>self, :eager_block=>eager_block, :id_map=>id_map} 3656 end 3657 3658 eager_load_data 3659 end
Prepare a hash loaders and eager options which will be used to implement the eager loading.