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 based on columns in associated tables. #eager_graph loads all records in one query. Using #eager_graph you can filter based on columns in associated tables. However, #eager_graph can be slower than #eager, especially if multiple *_to_many associations are joined.

You can cascade the eager loading (loading associations’ associations) 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

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(obj) ⇒ Object

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



1025
1026
1027
# File 'lib/sequel/model/associations.rb', line 1025

def self.extended(obj)
  obj.def_mutation_method(:eager, :eager_graph)
end

Instance Method Details

#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 *_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.



1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
# File 'lib/sequel/model/associations.rb', line 1055

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 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 *_to_many associations, as you can create large cartesian products. If you must graph multiple *_to_many associations, make sure your filters are specific 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 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 model object values).



1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
# File 'lib/sequel/model/associations.rb', line 1092

def eager_graph(*associations)
  table_name = model.table_name
  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=>model.table_name, :alias_association_type_map=>{}, :alias_association_name_map=>{}, :reciprocals=>{}, :cartesian_product_number=>0})
  end
  ds.eager_graph_associations(ds, model, table_name, [], *associations)
end

#ungraphedObject

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.



1111
1112
1113
# File 'lib/sequel/model/associations.rb', line 1111

def ungraphed
  super.clone(:eager_graph=>nil)
end