Class Index [+]

Quicksearch

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(: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.filter{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.filter{year > 1990}}=>{:tracks => :genre}})

Public Class Methods

extended(obj) click to toggle source

Add the eager! and eager_graph! mutation methods to the dataset.

      # File lib/sequel/model/associations.rb, line 1728
1728:         def self.extended(obj)
1729:           obj.def_mutation_method(:eager, :eager_graph)
1730:         end

Public Instance Methods

complex_expression_sql_append(sql, op, args) click to toggle source

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, line 1739
1739:         def complex_expression_sql_append(sql, op, args)
1740:           r = args.at(1)
1741:           if (((op == :'=' || op == :'!=') and r.is_a?(Sequel::Model)) ||
1742:               (multiple = ((op == :IN || op == :'NOT IN') and ((is_ds = r.is_a?(Sequel::Dataset)) or r.all?{|x| x.is_a?(Sequel::Model)}))))
1743:             l = args.at(0)
1744:             if ar = model.association_reflections[l]
1745:               if multiple
1746:                 klass = ar.associated_class
1747:                 if is_ds
1748:                   if r.respond_to?(:model)
1749:                     unless r.model <= klass
1750:                       # A dataset for a different model class, could be a valid regular query
1751:                       return super
1752:                     end
1753:                   else
1754:                     # Not a model dataset, could be a valid regular query
1755:                     return super
1756:                   end
1757:                 else
1758:                   unless r.all?{|x| x.is_a?(klass)}
1759:                     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}"
1760:                   end
1761:                 end
1762:               elsif !r.is_a?(ar.associated_class)
1763:                 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}"
1764:               end
1765: 
1766:               if exp = association_filter_expression(op, ar, r)
1767:                 literal_append(sql, exp)
1768:               else
1769:                 raise Sequel::Error, "invalid association type #{ar[:type].inspect} for association #{l.inspect} used in dataset filter for model #{model.inspect}"
1770:               end
1771:             elsif multiple && (is_ds || r.empty?)
1772:               # Not a query designed for this support, could be a valid regular query
1773:               super
1774:             else
1775:               raise Sequel::Error, "invalid association #{l.inspect} used in dataset filter for model #{model.inspect}"
1776:             end
1777:           else
1778:             super
1779:           end
1780:         end
eager(*associations) click to toggle source

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 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. Eager also works on a limited dataset, but does not use any :limit options for associations. If the association uses a block or has an :eager_block argument, it is used.

      # File lib/sequel/model/associations.rb, line 1808
1808:         def eager(*associations)
1809:           opt = @opts[:eager]
1810:           opt = opt ? opt.dup : {}
1811:           associations.flatten.each do |association|
1812:             case association
1813:               when Symbol
1814:                 check_association(model, association)
1815:                 opt[association] = nil
1816:               when Hash
1817:                 association.keys.each{|assoc| check_association(model, assoc)}
1818:                 opt.merge!(association)
1819:               else raise(Sequel::Error, 'Associations must be in the form of a symbol or hash')
1820:             end
1821:           end
1822:           clone(:eager=>opt)
1823:         end
eager_graph(*associations) click to toggle source

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.

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 you have a large database.

Each association’s order, if definied, is respected. eager_graph probably won’t work correctly on a limited dataset, unless you are only graphing many_to_one and one_to_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.

      # File lib/sequel/model/associations.rb, line 1845
1845:         def eager_graph(*associations)
1846:           ds = if eg = @opts[:eager_graph]
1847:             eg = eg.dup
1848:             [:requirements, :reflections, :reciprocals].each{|k| eg[k] = eg[k].dup}
1849:             clone(:eager_graph=>eg)
1850:           else
1851:             # Each of the following have a symbol key for the table alias, with the following values: 
1852:             # :reciprocals - the reciprocal instance variable to use for this association
1853:             # :reflections - AssociationReflection instance related to this association
1854:             # :requirements - array of requirements for this association
1855:             clone(:eager_graph=>{:requirements=>{}, :master=>alias_symbol(first_source), :reflections=>{}, :reciprocals=>{}, :cartesian_product_number=>0})
1856:           end
1857:           ds.eager_graph_associations(ds, model, ds.opts[:eager_graph][:master], [], *associations)
1858:         end
ungraphed() click to toggle source

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, line 1864
1864:         def ungraphed
1865:           super.clone(:eager_graph=>nil)
1866:         end

Protected Instance Methods

eager_graph_association(ds, model, ta, requirements, r, *associations) click to toggle source

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

*associations

any associations dependent on this one

      # File lib/sequel/model/associations.rb, line 1882
1882:         def eager_graph_association(ds, model, ta, requirements, r, *associations)
1883:           assoc_name = r[:name]
1884:           assoc_table_alias = ds.unused_table_alias(r[:graph_alias_base])
1885:           loader = r[:eager_grapher]
1886:           if !associations.empty?
1887:             if associations.first.respond_to?(:call)
1888:               callback = associations.first
1889:               associations = {}
1890:             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)
1891:               callback, assoc = pr_assoc
1892:               associations = assoc.is_a?(Array) ? assoc : [assoc]
1893:             end
1894:           end
1895:           ds = if loader.arity == 1
1896:             loader.call(:self=>ds, :table_alias=>assoc_table_alias, :implicit_qualifier=>ta, :callback=>callback)
1897:           else
1898:             loader.call(ds, assoc_table_alias, ta)
1899:           end
1900:           ds = ds.order_more(*qualified_expression(r[:order], assoc_table_alias)) if r[:order] and r[:order_eager_graph]
1901:           eager_graph = ds.opts[:eager_graph]
1902:           eager_graph[:requirements][assoc_table_alias] = requirements.dup
1903:           eager_graph[:reflections][assoc_table_alias] = r
1904:           eager_graph[:cartesian_product_number] += r[:cartesian_product_number] || 2
1905:           ds = ds.eager_graph_associations(ds, r.associated_class, assoc_table_alias, requirements + [assoc_table_alias], *associations) unless associations.empty?
1906:           ds
1907:         end
eager_graph_associations(ds, model, ta, requirements, *associations) click to toggle source

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, line 1918
1918:         def eager_graph_associations(ds, model, ta, requirements, *associations)
1919:           return ds if associations.empty?
1920:           associations.flatten.each do |association|
1921:             ds = case association
1922:             when Symbol
1923:               ds.eager_graph_association(ds, model, ta, requirements, check_association(model, association))
1924:             when Hash
1925:               association.each do |assoc, assoc_assocs|
1926:                 ds = ds.eager_graph_association(ds, model, ta, requirements, check_association(model, assoc), assoc_assocs)
1927:               end
1928:               ds
1929:             else raise(Sequel::Error, 'Associations must be in the form of a symbol or hash')
1930:             end
1931:           end
1932:           ds
1933:         end
eager_graph_build_associations(hashes) click to toggle source

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, line 1937
1937:         def eager_graph_build_associations(hashes)
1938:           hashes.replace(EagerGraphLoader.new(self).load(hashes))
1939:         end

Private Instance Methods

association_filter_expression(op, ref, obj) click to toggle source

Return an expression for filtering by the given association reflection and associated object.

      # File lib/sequel/model/associations.rb, line 1944
1944:         def association_filter_expression(op, ref, obj)
1945:           meth = :"#{ref[:type]}_association_filter_expression"
1946:           send(meth, op, ref, obj) if respond_to?(meth, true)
1947:         end
association_filter_handle_inversion(op, exp, cols) click to toggle source

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, line 1951
1951:         def association_filter_handle_inversion(op, exp, cols)
1952:           if op == :'!=' || op == :'NOT IN'
1953:             if exp == SQL::Constants::FALSE
1954:               ~exp
1955:             else
1956:               ~exp | Sequel::SQL::BooleanExpression.from_value_pairs(cols.zip([]), :OR)
1957:             end
1958:           else
1959:             exp
1960:           end
1961:         end
association_filter_key_expression(keys, meths, obj) click to toggle source

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, line 1966
1966:         def association_filter_key_expression(keys, meths, obj)
1967:           vals = if obj.is_a?(Sequel::Dataset)
1968:             {(keys.length == 1 ? keys.first : keys)=>obj.select(*meths).exclude(Sequel::SQL::BooleanExpression.from_value_pairs(meths.zip([]), :OR))}
1969:           else
1970:             vals = Array(obj).reject{|o| !meths.all?{|m| o.send(m)}}
1971:             return SQL::Constants::FALSE if vals.empty?
1972:             if obj.is_a?(Array)
1973:               if keys.length == 1
1974:                 meth = meths.first
1975:                 {keys.first=>vals.map{|o| o.send(meth)}}
1976:               else
1977:                 {keys=>vals.map{|o| meths.map{|m| o.send(m)}}}
1978:               end  
1979:             else
1980:               keys.zip(meths.map{|k| obj.send(k)})
1981:             end
1982:           end
1983:           SQL::BooleanExpression.from_value_pairs(vals)
1984:         end
check_association(model, association) click to toggle source

Make sure the association is valid for this model, and return the related AssociationReflection.

      # File lib/sequel/model/associations.rb, line 1987
1987:         def check_association(model, association)
1988:           raise(Sequel::UndefinedAssociation, "Invalid association #{association} for #{model.name}") unless reflection = model.association_reflection(association)
1989:           raise(Sequel::Error, "Eager loading is not allowed for #{model.name} association #{association}") if reflection[:allow_eager] == false
1990:           reflection
1991:         end
eager_load(a, eager_assoc=@opts[:eager]) click to toggle source

Eagerly load all specified associations

      # File lib/sequel/model/associations.rb, line 1994
1994:         def eager_load(a, eager_assoc=@opts[:eager])
1995:           return if a.empty?
1996:           # Key is foreign/primary key name symbol
1997:           # Value is hash with keys being foreign/primary key values (generally integers)
1998:           #  and values being an array of current model objects with that
1999:           #  specific foreign/primary key
2000:           key_hash = {}
2001:           # Reflections for all associations to eager load
2002:           reflections = eager_assoc.keys.collect{|assoc| model.association_reflection(assoc) || (raise Sequel::UndefinedAssociation, "Model: #{self}, Association: #{assoc}")}
2003:       
2004:           # Populate keys to monitor
2005:           reflections.each{|reflection| key_hash[reflection.eager_loader_key] ||= Hash.new{|h,k| h[k] = []}}
2006:           
2007:           # Associate each object with every key being monitored
2008:           a.each do |rec|
2009:             key_hash.each do |key, id_map|
2010:               case key
2011:               when Array
2012:                 id_map[key.map{|k| rec[k]}] << rec if key.all?{|k| rec[k]}
2013:               when Symbol
2014:                 id_map[rec[key]] << rec if rec[key]
2015:               end
2016:             end
2017:           end
2018:           
2019:           reflections.each do |r|
2020:             loader = r[:eager_loader]
2021:             associations = eager_assoc[r[:name]]
2022:             if associations.respond_to?(:call)
2023:               eager_block = associations
2024:               associations = {}
2025:             elsif associations.is_a?(Hash) && associations.length == 1 && (pr_assoc = associations.to_a.first) && pr_assoc.first.respond_to?(:call)
2026:               eager_block, associations = pr_assoc
2027:             end
2028:             if loader.arity == 1
2029:               loader.call(:key_hash=>key_hash, :rows=>a, :associations=>associations, :self=>self, :eager_block=>eager_block)
2030:             else
2031:               loader.call(key_hash, a, associations)
2032:             end
2033:             a.each{|object| object.send(:run_association_callbacks, r, :after_load, object.associations[r[:name]])} unless r[:after_load].empty?
2034:           end 
2035:         end
graph_each(&block) click to toggle source

Return plain hashes instead of calling the row_proc if eager_graph is being used.

      # File lib/sequel/model/associations.rb, line 2038
2038:         def graph_each(&block)
2039:           @opts[:eager_graph] ? fetch_rows(select_sql, &block) : super
2040:         end
many_to_many_association_filter_expression(op, ref, obj) click to toggle source

Return a subquery expression for filering by a many_to_many association

      # File lib/sequel/model/associations.rb, line 2043
2043:         def many_to_many_association_filter_expression(op, ref, obj)
2044:           lpks, lks, rks = ref.values_at(:left_primary_keys, :left_keys, :right_keys)
2045:           jt = ref.join_table_alias
2046:           lpks = lpks.first if lpks.length == 1
2047:           lpks = ref.qualify(model.table_name, lpks)
2048:           meths = ref.right_primary_keys
2049:           meths = ref.qualify(obj.model.table_name, meths) if obj.is_a?(Sequel::Dataset)
2050:           exp = association_filter_key_expression(ref.qualify(jt, rks), meths, obj)
2051:           if exp == SQL::Constants::FALSE
2052:             association_filter_handle_inversion(op, exp, Array(lpks))
2053:           else
2054:             association_filter_handle_inversion(op, SQL::BooleanExpression.from_value_pairs(lpks=>model.db.from(ref[:join_table]).select(*ref.qualify(jt, lks)).where(exp).exclude(SQL::BooleanExpression.from_value_pairs(ref.qualify(jt, lks).zip([]), :OR))), Array(lpks))
2055:           end
2056:         end
many_to_one_association_filter_expression(op, ref, obj) click to toggle source

Return a simple equality expression for filering by a many_to_one association

      # File lib/sequel/model/associations.rb, line 2059
2059:         def many_to_one_association_filter_expression(op, ref, obj)
2060:           keys = ref.qualify(model.table_name, ref[:keys])
2061:           meths = ref.primary_keys
2062:           meths = ref.qualify(obj.model.table_name, meths) if obj.is_a?(Sequel::Dataset)
2063:           association_filter_handle_inversion(op, association_filter_key_expression(keys, meths, obj), keys)
2064:         end
one_to_many_association_filter_expression(op, ref, obj) click to toggle source

Return a simple equality expression for filering by a one_to_* association

      # File lib/sequel/model/associations.rb, line 2067
2067:         def one_to_many_association_filter_expression(op, ref, obj)
2068:           keys = ref.qualify(model.table_name, ref[:primary_keys])
2069:           meths = ref[:keys]
2070:           meths = ref.qualify(obj.model.table_name, meths) if obj.is_a?(Sequel::Dataset)
2071:           association_filter_handle_inversion(op, association_filter_key_expression(keys, meths, obj), keys)
2072:         end
one_to_one_association_filter_expression(op, ref, obj) click to toggle source
post_load(all_records) click to toggle source

Build associations from the graph if # was used, and/or load other associations if # was used.

      # File lib/sequel/model/associations.rb, line 2077
2077:         def post_load(all_records)
2078:           eager_graph_build_associations(all_records) if @opts[:eager_graph]
2079:           eager_load(all_records) if @opts[:eager]
2080:           super
2081:         end

Disabled; run with --debug to generate this.

[Validate]

Generated with the Darkfish Rdoc Generator 1.1.6.