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 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_graph(: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}})

Instance Method Summary collapse

Instance Method Details

#as_hash(key_column = nil, value_column = nil, opts = OPTS) ⇒ Object

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



3319
3320
3321
3322
3323
3324
3325
# File 'lib/sequel/model/associations.rb', line 3319

def as_hash(key_column=nil, value_column=nil, opts=OPTS)
  if (@opts[:eager_graph] || @opts[:eager]) && !opts.has_key?(:all)
    opts = Hash[opts]
    opts[:all] = true
  end
  super
end

#association_join(*associations) ⇒ Object

Adds one or more INNER JOINs to the existing dataset using the keys and conditions specified by the given association(s). Take the same arguments as eager_graph, and operates similarly, but only adds the joins as opposed to making the other changes (such as adding selected columns and setting up eager loading).

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

Examples:

# For each album, association_join load the artist
Album.association_join(:artist).all
# SELECT *
# FROM albums
# INNER JOIN artists AS artist ON (artists.id = albums.artist_id)

# For each album, association_join load the artist, using a specified alias
Album.association_join(Sequel[:artist].as(:a)).all
# SELECT *
# FROM albums
# INNER JOIN artists AS a ON (a.id = albums.artist_id)

# For each album, association_join load the artist and genre
Album.association_join(:artist, :genre).all
Album.association_join(:artist).association_join(:genre).all
# SELECT *
# FROM albums
# INNER JOIN artists AS artist ON (artist.id = albums.artist_id)
# INNER JOIN genres AS genre ON (genre.id = albums.genre_id)

# For each artist, association_join load albums and tracks for each album
Artist.association_join(albums: :tracks).all
# SELECT *
# FROM artists 
# INNER JOIN albums ON (albums.artist_id = artists.id)
# INNER JOIN tracks ON (tracks.album_id = albums.id)

# For each artist, association_join load albums, tracks for each album, and genre for each track
Artist.association_join(albums: {tracks: :genre}).all
# SELECT *
# FROM artists 
# INNER JOIN albums ON (albums.artist_id = artists.id)
# INNER JOIN tracks ON (tracks.album_id = albums.id)
# INNER JOIN genres AS genre ON (genre.id = tracks.genre_id)

# For each artist, association_join load albums with year > 1990
Artist.association_join(albums: proc{|ds| ds.where{year > 1990}}).all
# SELECT *
# FROM artists 
# INNER JOIN (
#   SELECT * FROM albums WHERE (year > 1990)
# ) AS albums ON (albums.artist_id = artists.id)

# For each artist, association_join load albums and tracks 1-10 for each album
Artist.association_join(albums: {tracks: proc{|ds| ds.where(number: 1..10)}}).all
# SELECT *
# FROM artists 
# INNER JOIN albums ON (albums.artist_id = artists.id)
# INNER JOIN (
#   SELECT * FROM tracks WHERE ((number >= 1) AND (number <= 10))
# ) AS tracks ON (tracks.albums_id = albums.id)

# For each artist, association_join load albums with year > 1990, and tracks for those albums
Artist.association_join(albums: {proc{|ds| ds.where{year > 1990}}=>:tracks}).all
# SELECT *
# FROM artists 
# INNER JOIN (
#   SELECT * FROM albums WHERE (year > 1990)
# ) AS albums ON (albums.artist_id = artists.id)
# INNER JOIN tracks ON (tracks.album_id = albums.id)


3025
3026
3027
# File 'lib/sequel/model/associations.rb', line 3025

def association_join(*associations)
  association_inner_join(*associations)
end

#complex_expression_sql_append(sql, op, args) ⇒ Object

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.



3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
# File 'lib/sequel/model/associations.rb', line 3036

def complex_expression_sql_append(sql, op, args)
  r = args[1]
  if (((op == :'=' || op == :'!=') && r.is_a?(Sequel::Model)) ||
      (multiple = ((op == :IN || op == :'NOT IN') && ((is_ds = r.is_a?(Sequel::Dataset)) || (r.respond_to?(:all?) && r.all?{|x| x.is_a?(Sequel::Model)})))))
    l = args[0]
    if ar = model.association_reflections[l]
      raise Error, "filtering by associations is not allowed for #{ar.inspect}" if ar[:allow_filtering_by] == false

      if multiple
        klass = ar.associated_class
        if is_ds
          if r.respond_to?(:model)
            unless r.model <= klass
              # A dataset for a different model class, could be a valid regular query
              return super
            end
          else
            # Not a model dataset, could be a valid regular query
            return super
          end
        else
          unless r.all?{|x| x.is_a?(klass)}
            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}"
          end
        end
      elsif !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(op, ar, r)
        literal_append(sql, exp)
      else
        raise Sequel::Error, "invalid association type #{ar[:type].inspect} for association #{l.inspect} used in dataset filter for model #{model.inspect}"
      end
    elsif multiple && (is_ds || r.empty?)
      # Not a query designed for this support, could be a valid regular query
      super
    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 current 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.

To modify the associated dataset that will be used for the eager load, you should use a hash for the association, with the key being the association name symbol, and the value being a callable object that is called with the associated dataset and should return a modified dataset. If that association also has dependent associations, instead of a callable object, use a hash with the callable object being the key, and the dependent association(s) as the value.

Examples:

# For each album, eager load the artist
Album.eager(:artist).all
# SELECT * FROM albums
# SELECT * FROM artists WHERE (id IN (...))

# For each album, eager load the artist and genre
Album.eager(:artist, :genre).all
Album.eager(:artist).eager(:genre).all
# SELECT * FROM albums
# SELECT * FROM artists WHERE (id IN (...))
# SELECT * FROM genres WHERE (id IN (...))

# For each artist, eager load albums and tracks for each album
Artist.eager(albums: :tracks).all
# SELECT * FROM artists
# SELECT * FROM albums WHERE (artist_id IN (...))
# SELECT * FROM tracks WHERE (album_id IN (...))

# For each artist, eager load albums, tracks for each album, and genre for each track
Artist.eager(albums: {tracks: :genre}).all
# SELECT * FROM artists
# SELECT * FROM albums WHERE (artist_id IN (...))
# SELECT * FROM tracks WHERE (album_id IN (...))
# SELECT * FROM genre WHERE (id IN (...))

# For each artist, eager load albums with year > 1990
Artist.eager(albums: proc{|ds| ds.where{year > 1990}}).all
# SELECT * FROM artists
# SELECT * FROM albums WHERE ((year > 1990) AND (artist_id IN (...)))

# For each artist, eager load albums and tracks 1-10 for each album
Artist.eager(albums: {tracks: proc{|ds| ds.where(number: 1..10)}}).all
# SELECT * FROM artists
# SELECT * FROM albums WHERE (artist_id IN (...))
# SELECT * FROM tracks WHERE ((number >= 1) AND (number <= 10) AND (album_id IN (...)))

# For each artist, eager load albums with year > 1990, and tracks for those albums
Artist.eager(albums: {proc{|ds| ds.where{year > 1990}}=>:tracks}).all
# SELECT * FROM artists
# SELECT * FROM albums WHERE ((year > 1990) AND (artist_id IN (...)))
# SELECT * FROM albums WHERE (artist_id IN (...))


3156
3157
3158
3159
3160
3161
# File 'lib/sequel/model/associations.rb', line 3156

def eager(*associations)
  opts = @opts[:eager]
  association_opts = eager_options_for_associations(associations)
  opts = opts ? opts.merge(association_opts) : association_opts
  clone(:eager=>opts.freeze)
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, or if you have done comparative benchmarking and determined it is faster.

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 the datasets are large.

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.

To modify the associated dataset that will be joined to the current dataset, you should use a hash for the association, with the key being the association name symbol, and the value being a callable object that is called with the associated dataset and should return a modified dataset. If that association also has dependent associations, instead of a callable object, use a hash with the callable object being the key, and the dependent association(s) as the value.

You can specify an custom alias and/or join type on a per-association basis by providing an Sequel::SQL::AliasedExpression object instead of an a Symbol for the association name.

You cannot mix calls to eager_graph and graph on the same dataset.

Examples:

# For each album, eager_graph load the artist
Album.eager_graph(:artist).all
# SELECT ...
# FROM albums
# LEFT OUTER JOIN artists AS artist ON (artists.id = albums.artist_id)

# For each album, eager_graph load the artist, using a specified alias
Album.eager_graph(Sequel[:artist].as(:a)).all
# SELECT ...
# FROM albums
# LEFT OUTER JOIN artists AS a ON (a.id = albums.artist_id)

# For each album, eager_graph load the artist, using a specified alias
# and custom join type

Album.eager_graph(Sequel[:artist].as(:a, join_type: :inner)).all
# SELECT ...
# FROM albums
# INNER JOIN artists AS a ON (a.id = albums.artist_id)

# For each album, eager_graph load the artist and genre
Album.eager_graph(:artist, :genre).all
Album.eager_graph(:artist).eager_graph(:genre).all
# SELECT ...
# FROM albums
# LEFT OUTER JOIN artists AS artist ON (artist.id = albums.artist_id)
# LEFT OUTER JOIN genres AS genre ON (genre.id = albums.genre_id)

# For each artist, eager_graph load albums and tracks for each album
Artist.eager_graph(albums: :tracks).all
# SELECT ...
# FROM artists 
# LEFT OUTER JOIN albums ON (albums.artist_id = artists.id)
# LEFT OUTER JOIN tracks ON (tracks.album_id = albums.id)

# For each artist, eager_graph load albums, tracks for each album, and genre for each track
Artist.eager_graph(albums: {tracks: :genre}).all
# SELECT ...
# FROM artists 
# LEFT OUTER JOIN albums ON (albums.artist_id = artists.id)
# LEFT OUTER JOIN tracks ON (tracks.album_id = albums.id)
# LEFT OUTER JOIN genres AS genre ON (genre.id = tracks.genre_id)

# For each artist, eager_graph load albums with year > 1990
Artist.eager_graph(albums: proc{|ds| ds.where{year > 1990}}).all
# SELECT ...
# FROM artists 
# LEFT OUTER JOIN (
#   SELECT * FROM albums WHERE (year > 1990)
# ) AS albums ON (albums.artist_id = artists.id)

# For each artist, eager_graph load albums and tracks 1-10 for each album
Artist.eager_graph(albums: {tracks: proc{|ds| ds.where(number: 1..10)}}).all
# SELECT ...
# FROM artists 
# LEFT OUTER JOIN albums ON (albums.artist_id = artists.id)
# LEFT OUTER JOIN (
#   SELECT * FROM tracks WHERE ((number >= 1) AND (number <= 10))
# ) AS tracks ON (tracks.albums_id = albums.id)

# For each artist, eager_graph load albums with year > 1990, and tracks for those albums
Artist.eager_graph(albums: {proc{|ds| ds.where{year > 1990}}=>:tracks}).all
# SELECT ...
# FROM artists 
# LEFT OUTER JOIN (
#   SELECT * FROM albums WHERE (year > 1990)
# ) AS albums ON (albums.artist_id = artists.id)
# LEFT OUTER JOIN tracks ON (tracks.album_id = albums.id)


3266
3267
3268
# File 'lib/sequel/model/associations.rb', line 3266

def eager_graph(*associations)
  eager_graph_with_options(associations)
end

#eager_graph_with_options(associations, opts = OPTS) ⇒ Object

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.



3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
# File 'lib/sequel/model/associations.rb', line 3290

def eager_graph_with_options(associations, opts=OPTS)
  return self if associations.empty?

  opts = opts.dup unless opts.frozen?
  associations = [associations] unless associations.is_a?(Array)
  ds = if eg = @opts[:eager_graph]
    eg = eg.dup
    [:requirements, :reflections, :reciprocals, :limits].each{|k| eg[k] = eg[k].dup}
    eg[:local] = opts
    ds = clone(:eager_graph=>eg)
    ds.eager_graph_associations(ds, model, ds.opts[:eager_graph][:master], [], *associations)
  else
    # Each of the following have a symbol key for the table alias, with the following values: 
    # :reciprocals :: the reciprocal value to use for this association
    # :reflections :: AssociationReflection instance related to this association
    # :requirements :: array of requirements for this association
    # :limits :: Any limit/offset array slicing that need to be handled in ruby land after loading
    opts = {:requirements=>{}, :master=>alias_symbol(first_source), :reflections=>{}, :reciprocals=>{}, :limits=>{}, :local=>opts, :cartesian_product_number=>0, :row_proc=>row_proc}
    ds = clone(:eager_graph=>opts)
    ds = ds.eager_graph_associations(ds, model, ds.opts[:eager_graph][:master], [], *associations).naked
  end

  ds.opts[:eager_graph].freeze
  ds.opts[:eager_graph].each_value{|v| v.freeze if v.is_a?(Hash)}
  ds
end

#to_hash_groups(key_column, value_column = nil, opts = OPTS) ⇒ Object

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



3329
3330
3331
3332
3333
3334
3335
# File 'lib/sequel/model/associations.rb', line 3329

def to_hash_groups(key_column, value_column=nil, opts=OPTS)
  if (@opts[:eager_graph] || @opts[:eager]) && !opts.has_key?(:all)
    opts = Hash[opts]
    opts[:all] = true
  end
  super
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.



3341
3342
3343
3344
3345
3346
3347
# File 'lib/sequel/model/associations.rb', line 3341

def ungraphed
  ds = super.clone(:eager_graph=>nil)
  if (eg = @opts[:eager_graph]) && (rp = eg[:row_proc])
    ds = ds.with_row_proc(rp)
  end
  ds
end