| Module | Sequel::Model::Associations::DatasetMethods |
| In: |
lib/sequel/model/associations.rb
|
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.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}})
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 1818
1818: def complex_expression_sql_append(sql, op, args)
1819: r = args.at(1)
1820: if (((op == '=''=' || op == '!=''!=') and r.is_a?(Sequel::Model)) ||
1821: (multiple = ((op == :IN || op == 'NOT IN''NOT IN') and ((is_ds = r.is_a?(Sequel::Dataset)) or r.all?{|x| x.is_a?(Sequel::Model)}))))
1822: l = args.at(0)
1823: if ar = model.association_reflections[l]
1824: if multiple
1825: klass = ar.associated_class
1826: if is_ds
1827: if r.respond_to?(:model)
1828: unless r.model <= klass
1829: # A dataset for a different model class, could be a valid regular query
1830: return super
1831: end
1832: else
1833: # Not a model dataset, could be a valid regular query
1834: return super
1835: end
1836: else
1837: unless r.all?{|x| x.is_a?(klass)}
1838: 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}"
1839: end
1840: end
1841: elsif !r.is_a?(ar.associated_class)
1842: 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}"
1843: end
1844:
1845: if exp = association_filter_expression(op, ar, r)
1846: literal_append(sql, exp)
1847: else
1848: raise Sequel::Error, "invalid association type #{ar[:type].inspect} for association #{l.inspect} used in dataset filter for model #{model.inspect}"
1849: end
1850: elsif multiple && (is_ds || r.empty?)
1851: # Not a query designed for this support, could be a valid regular query
1852: super
1853: else
1854: raise Sequel::Error, "invalid association #{l.inspect} used in dataset filter for model #{model.inspect}"
1855: end
1856: else
1857: super
1858: end
1859: 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 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.
# File lib/sequel/model/associations.rb, line 1886
1886: def eager(*associations)
1887: opt = @opts[:eager]
1888: opt = opt ? opt.dup : {}
1889: associations.flatten.each do |association|
1890: case association
1891: when Symbol
1892: check_association(model, association)
1893: opt[association] = nil
1894: when Hash
1895: association.keys.each{|assoc| check_association(model, assoc)}
1896: opt.merge!(association)
1897: else
1898: raise(Sequel::Error, 'Associations must be in the form of a symbol or hash')
1899: end
1900: end
1901: clone(:eager=>opt)
1902: 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.
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 1924
1924: def eager_graph(*associations)
1925: ds = if eg = @opts[:eager_graph]
1926: eg = eg.dup
1927: [:requirements, :reflections, :reciprocals].each{|k| eg[k] = eg[k].dup}
1928: clone(:eager_graph=>eg)
1929: else
1930: # Each of the following have a symbol key for the table alias, with the following values:
1931: # :reciprocals - the reciprocal instance variable to use for this association
1932: # :reflections - AssociationReflection instance related to this association
1933: # :requirements - array of requirements for this association
1934: clone(:eager_graph=>{:requirements=>{}, :master=>alias_symbol(first_source), :reflections=>{}, :reciprocals=>{}, :cartesian_product_number=>0})
1935: end
1936: ds.eager_graph_associations(ds, model, ds.opts[:eager_graph][:master], [], *associations)
1937: 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, line 1943
1943: def ungraphed
1944: super.clone(:eager_graph=>nil)
1945: 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 and the alias base as the aliaz. |
| *associations : | any associations dependent on this one |
# File lib/sequel/model/associations.rb, line 1962
1962: def eager_graph_association(ds, model, ta, requirements, r, *associations)
1963: if r.is_a?(SQL::AliasedExpression)
1964: alias_base = r.aliaz
1965: r = r.expression
1966: else
1967: alias_base = r[:graph_alias_base]
1968: end
1969: assoc_table_alias = ds.unused_table_alias(alias_base)
1970: loader = r[:eager_grapher]
1971: if !associations.empty?
1972: if associations.first.respond_to?(:call)
1973: callback = associations.first
1974: associations = {}
1975: 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)
1976: callback, assoc = pr_assoc
1977: associations = assoc.is_a?(Array) ? assoc : [assoc]
1978: end
1979: end
1980: ds = if loader.arity == 1
1981: loader.call(:self=>ds, :table_alias=>assoc_table_alias, :implicit_qualifier=>ta, :callback=>callback)
1982: else
1983: loader.call(ds, assoc_table_alias, ta)
1984: end
1985: ds = ds.order_more(*qualified_expression(r[:order], assoc_table_alias)) if r[:order] and r[:order_eager_graph]
1986: eager_graph = ds.opts[:eager_graph]
1987: eager_graph[:requirements][assoc_table_alias] = requirements.dup
1988: eager_graph[:reflections][assoc_table_alias] = r
1989: eager_graph[:cartesian_product_number] += r[:cartesian_product_number] || 2
1990: ds = ds.eager_graph_associations(ds, r.associated_class, assoc_table_alias, requirements + [assoc_table_alias], *associations) unless associations.empty?
1991: ds
1992: 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, line 2003
2003: def eager_graph_associations(ds, model, ta, requirements, *associations)
2004: return ds if associations.empty?
2005: associations.flatten.each do |association|
2006: ds = case association
2007: when Symbol, SQL::AliasedExpression
2008: ds.eager_graph_association(ds, model, ta, requirements, eager_graph_check_association(model, association))
2009: when Hash
2010: association.each do |assoc, assoc_assocs|
2011: ds = ds.eager_graph_association(ds, model, ta, requirements, eager_graph_check_association(model, assoc), assoc_assocs)
2012: end
2013: ds
2014: else
2015: raise(Sequel::Error, 'Associations must be in the form of a symbol or hash')
2016: end
2017: end
2018: ds
2019: 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, line 2023
2023: def eager_graph_build_associations(hashes)
2024: hashes.replace(EagerGraphLoader.new(self).load(hashes))
2025: end