Module: Sequel::Model::Associations::DatasetMethods
- Defined in:
- lib/sequel/model/associations.rb
Overview
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
can be 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}})
Class Method Summary collapse
-
.extended(obj) ⇒ Object
Add the
eager!
andeager_graph!
mutation methods to the dataset.
Instance Method Summary collapse
-
#complex_expression_sql(op, args) ⇒ Object
If the expression is in the form
x = y
wherey
is aSequel::Model
instance, assumex
is an association symbol and look up the association reflection via the dataset’s model. -
#eager(*associations) ⇒ Object
The preferred eager loading method.
-
#eager_graph(*associations) ⇒ Object
The secondary eager loading method.
-
#ungraphed ⇒ Object
Do not attempt to split the result set into associations, just return results as simple objects.
Class Method Details
.extended(obj) ⇒ Object
Add the eager!
and eager_graph!
mutation methods to the dataset.
1329 1330 1331 |
# File 'lib/sequel/model/associations.rb', line 1329 def self.extended(obj) obj.def_mutation_method(:eager, :eager_graph) end |
Instance Method Details
#complex_expression_sql(op, args) ⇒ Object
If the expression is in the form x = y
where y
is a Sequel::Model
instance, 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.
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 |
# File 'lib/sequel/model/associations.rb', line 1417 def complex_expression_sql(op, args) if op == :'=' and args.at(1).is_a?(Sequel::Model) l, r = args if ar = model.association_reflections[l] unless r.is_a?(ar.associated_class) 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}" end if exp = association_filter_expression(ar, r) literal(exp) else raise Sequel::Error, "invalid association type #{ar[:type].inspect} for association #{l.inspect} used in dataset filter for model #{model.inspect}" end else raise Sequel::Error, "invalid association #{l.inspect} used in dataset filter for model #{model.inspect}" end else super end end |
#eager(*associations) ⇒ Object
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.
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 |
# File 'lib/sequel/model/associations.rb', line 1359 def eager(*associations) opt = @opts[:eager] opt = opt ? opt.dup : {} associations.flatten.each do |association| case association when Symbol check_association(model, association) opt[association] = nil when Hash association.keys.each{|assoc| check_association(model, assoc)} opt.merge!(association) else raise(Sequel::Error, 'Associations must be in the form of a symbol or hash') end end clone(:eager=>opt) end |
#eager_graph(*associations) ⇒ Object
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 builds an object graph using Dataset#graph
. Then it uses the graph to build the associations, and finally replaces the graph with a simple array of model objects.
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
, you will get a normal graphed result back (a hash with table alias symbol keys and model object values).
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 |
# File 'lib/sequel/model/associations.rb', line 1397 def eager_graph(*associations) ds = if @opts[:eager_graph] self else # Each of the following have a symbol key for the table alias, with the following values: # :reciprocals - the reciprocal instance variable to use for this association # :requirements - array of requirements for this association # :alias_association_type_map - the type of association for this association # :alias_association_name_map - the name of the association for this association clone(:eager_graph=>{:requirements=>{}, :master=>alias_symbol(first_source), :alias_association_type_map=>{}, :alias_association_name_map=>{}, :reciprocals=>{}, :cartesian_product_number=>0}) end ds.eager_graph_associations(ds, model, ds.opts[:eager_graph][:master], [], *associations) end |
#ungraphed ⇒ Object
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.
1442 1443 1444 |
# File 'lib/sequel/model/associations.rb', line 1442 def ungraphed super.clone(:eager_graph=>nil) end |