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}})

Methods

Public Instance methods

Adds one or more INNER JOINs to the existing dataset using the keys and conditions specified by the given association. 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

[Source]

      # File lib/sequel/model/associations.rb, line 2518
2518:         def association_join(*associations)
2519:           association_inner_join(*associations)
2520:         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, line 2529
2529:         def complex_expression_sql_append(sql, op, args)
2530:           r = args.at(1)
2531:           if (((op == '=''=' || op == '!=''!=') and r.is_a?(Sequel::Model)) ||
2532:               (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)}))))
2533:             l = args.at(0)
2534:             if ar = model.association_reflections[l]
2535:               if multiple
2536:                 klass = ar.associated_class
2537:                 if is_ds
2538:                   if r.respond_to?(:model)
2539:                     unless r.model <= klass
2540:                       # A dataset for a different model class, could be a valid regular query
2541:                       return super
2542:                     end
2543:                   else
2544:                     # Not a model dataset, could be a valid regular query
2545:                     return super
2546:                   end
2547:                 else
2548:                   unless r.all?{|x| x.is_a?(klass)}
2549:                     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}"
2550:                   end
2551:                 end
2552:               elsif !r.is_a?(ar.associated_class)
2553:                 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}"
2554:               end
2555: 
2556:               if exp = association_filter_expression(op, ar, r)
2557:                 literal_append(sql, exp)
2558:               else
2559:                 raise Sequel::Error, "invalid association type #{ar[:type].inspect} for association #{l.inspect} used in dataset filter for model #{model.inspect}"
2560:               end
2561:             elsif multiple && (is_ds || r.empty?)
2562:               # Not a query designed for this support, could be a valid regular query
2563:               super
2564:             else
2565:               raise Sequel::Error, "invalid association #{l.inspect} used in dataset filter for model #{model.inspect}"
2566:             end
2567:           else
2568:             super
2569:           end
2570:         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.

[Source]

      # File lib/sequel/model/associations.rb, line 2597
2597:         def eager(*associations)
2598:           opts = @opts[:eager]
2599:           association_opts = eager_options_for_associations(associations)
2600:           opts = opts ? Hash[opts].merge!(association_opts) : association_opts
2601:           clone(:eager=>opts)
2602:         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 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.

[Source]

      # File lib/sequel/model/associations.rb, line 2624
2624:         def eager_graph(*associations)
2625:           eager_graph_with_options(associations)
2626:         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, line 2648
2648:         def eager_graph_with_options(associations, opts=OPTS)
2649:           associations = [associations] unless associations.is_a?(Array)
2650:           if eg = @opts[:eager_graph]
2651:             eg = eg.dup
2652:             [:requirements, :reflections, :reciprocals, :limits].each{|k| eg[k] = eg[k].dup}
2653:             eg[:local] = opts
2654:             ds = clone(:eager_graph=>eg)
2655:             ds.eager_graph_associations(ds, model, ds.opts[:eager_graph][:master], [], *associations)
2656:           else
2657:             # Each of the following have a symbol key for the table alias, with the following values: 
2658:             # :reciprocals :: the reciprocal value to use for this association
2659:             # :reflections :: AssociationReflection instance related to this association
2660:             # :requirements :: array of requirements for this association
2661:             # :limits :: Any limit/offset array slicing that need to be handled in ruby land after loading
2662:             opts = {:requirements=>{}, :master=>alias_symbol(first_source), :reflections=>{}, :reciprocals=>{}, :limits=>{}, :local=>opts, :cartesian_product_number=>0, :row_proc=>row_proc}
2663:             ds = clone(:eager_graph=>opts)
2664:             ds.eager_graph_associations(ds, model, ds.opts[:eager_graph][:master], [], *associations).naked
2665:           end
2666:         end

If the dataset is being eagerly loaded, default to calling all instead of each.

[Source]

      # File lib/sequel/model/associations.rb, line 2670
2670:         def to_hash(key_column=nil, value_column=nil, opts=OPTS)
2671:           if (@opts[:eager_graph] || @opts[:eager]) && !opts.has_key?(:all)
2672:             opts = Hash[opts]
2673:             opts[:all] = true
2674:           end
2675:           super
2676:         end

If the dataset is being eagerly loaded, default to calling all instead of each.

[Source]

      # File lib/sequel/model/associations.rb, line 2680
2680:         def to_hash_groups(key_column, value_column=nil, opts=OPTS)
2681:           if (@opts[:eager_graph] || @opts[:eager]) && !opts.has_key?(:all)
2682:             opts = Hash[opts]
2683:             opts[:all] = true
2684:           end
2685:           super
2686:         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.

[Source]

      # File lib/sequel/model/associations.rb, line 2692
2692:         def ungraphed
2693:           ds = super.clone(:eager_graph=>nil)
2694:           if (eg = @opts[:eager_graph]) && (rp = eg[:row_proc])
2695:             ds.row_proc = rp
2696:           end
2697:           ds
2698:         end

Protected Instance methods

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

[Source]

      # File lib/sequel/model/associations.rb, line 2715
2715:         def eager_graph_association(ds, model, ta, requirements, r, *associations)
2716:           if r.is_a?(SQL::AliasedExpression)
2717:             alias_base = r.alias
2718:             r = r.expression
2719:           else
2720:             alias_base = r[:graph_alias_base]
2721:           end
2722:           assoc_table_alias = ds.unused_table_alias(alias_base)
2723:           loader = r[:eager_grapher]
2724:           if !associations.empty?
2725:             if associations.first.respond_to?(:call)
2726:               callback = associations.first
2727:               associations = {}
2728:             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)
2729:               callback, assoc = pr_assoc
2730:               associations = assoc.is_a?(Array) ? assoc : [assoc]
2731:             end
2732:           end
2733:           local_opts = ds.opts[:eager_graph][:local]
2734:           limit_strategy = r.eager_graph_limit_strategy(local_opts[:limit_strategy])
2735:           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=>local_opts[:join_type], :join_only=>local_opts[:join_only], :limit_strategy=>limit_strategy, :from_self_alias=>ds.opts[:eager_graph][:master])
2736:           if r[:order_eager_graph] && (order = r.fetch(:graph_order, r[:order]))
2737:             ds = ds.order_more(*qualified_expression(order, assoc_table_alias))
2738:           end
2739:           eager_graph = ds.opts[:eager_graph]
2740:           eager_graph[:requirements][assoc_table_alias] = requirements.dup
2741:           eager_graph[:reflections][assoc_table_alias] = r
2742:           if limit_strategy == :ruby
2743:             eager_graph[:limits][assoc_table_alias] = r.limit_and_offset 
2744:           end
2745:           eager_graph[:cartesian_product_number] += r[:cartesian_product_number] || 2
2746:           ds = ds.eager_graph_associations(ds, r.associated_class, assoc_table_alias, requirements + [assoc_table_alias], *associations) unless associations.empty?
2747:           ds
2748:         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, line 2759
2759:         def eager_graph_associations(ds, model, ta, requirements, *associations)
2760:           return ds if associations.empty?
2761:           associations.flatten.each do |association|
2762:             ds = case association
2763:             when Symbol, SQL::AliasedExpression
2764:               ds.eager_graph_association(ds, model, ta, requirements, eager_graph_check_association(model, association))
2765:             when Hash
2766:               association.each do |assoc, assoc_assocs|
2767:                 ds = ds.eager_graph_association(ds, model, ta, requirements, eager_graph_check_association(model, assoc), assoc_assocs)
2768:               end
2769:               ds
2770:             else
2771:               raise(Sequel::Error, 'Associations must be in the form of a symbol or hash')
2772:             end
2773:           end
2774:           ds
2775:         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.

[Source]

      # File lib/sequel/model/associations.rb, line 2779
2779:         def eager_graph_build_associations(hashes)
2780:           hashes.replace(EagerGraphLoader.new(self).load(hashes))
2781:         end

[Validate]