Module: Sequel::Model::Associations::DatasetMethods

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

### Methods

eager eager_graph eager_graph_association eager_graph_associations eager_graph_build_associations eager_unique_table_alias extended ungraphed

### Public Class methods

extended(obj)

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

[Source]

          # File lib/sequel/model/associations.rb, line 1148
    1148:         def self.extended(obj)
    1149:           obj.def_mutation_method(:eager, :eager_graph)
    1150:         end

### Public Instance methods

eager(*associations)

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.

[Source]

          # File lib/sequel/model/associations.rb, line 1178
    1178:         def eager(*associations)
    1179:           opt = @opts[:eager]
    1180:           opt = opt ? opt.dup : {}
    1181:           associations.flatten.each do |association|
    1182:             case association
    1183:               when Symbol
    1184:                 check_association(model, association)
    1185:                 opt[association] = nil
    1186:               when Hash
    1187:                 association.keys.each{|assoc| check_association(model, assoc)}
    1188:                 opt.merge!(association)
    1189:               else raise(Sequel::Error, 'Associations must be in the form of a symbol or hash')
    1190:             end
    1191:           end
    1192:           clone(:eager=>opt)
    1193:         end

eager_graph(*associations)

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

[Source]

          # File lib/sequel/model/associations.rb, line 1215
    1215:         def eager_graph(*associations)
    1216:           table_name = model.table_name
    1217:
    1218:           ds = if @opts[:eager_graph]
    1219:             self
    1220:           else
    1221:             # Each of the following have a symbol key for the table alias, with the following values:
    1222:             # :reciprocals - the reciprocal instance variable to use for this association
    1223:             # :requirements - array of requirements for this association
    1224:             # :alias_association_type_map - the type of association for this association
    1225:             # :alias_association_name_map - the name of the association for this association
    1226:             clone(:eager_graph=>{:requirements=>{}, :master=>table_name, :alias_association_type_map=>{}, :alias_association_name_map=>{}, :reciprocals=>{}, :cartesian_product_number=>0})
    1227:           end
    1228:           ds.eager_graph_associations(ds, model, table_name, [], *associations)
    1229:         end

ungraphed()

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 1235
    1235:         def ungraphed
    1236:           super.clone(:eager_graph=>nil)
    1237:         end

### Protected Instance methods

eager_graph_association(ds, model, ta, requirements, r, *associations)

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
- *associations - any associations dependent on this one

[Source]

          # File lib/sequel/model/associations.rb, line 1253
    1253:         def eager_graph_association(ds, model, ta, requirements, r, *associations)
    1254:           klass = r.associated_class
    1255:           assoc_name = r[:name]
    1256:           assoc_table_alias = ds.eager_unique_table_alias(ds, assoc_name)
    1257:           ds = r[:eager_grapher].call(ds, assoc_table_alias, ta)
    1258:           ds = ds.order_more(*Array(r[:order]).map{|c| eager_graph_qualify_order(assoc_table_alias, c)}) if r[:order] and r[:order_eager_graph]
    1259:           eager_graph = ds.opts[:eager_graph]
    1260:           eager_graph[:requirements][assoc_table_alias] = requirements.dup
    1261:           eager_graph[:alias_association_name_map][assoc_table_alias] = assoc_name
    1262:           eager_graph[:alias_association_type_map][assoc_table_alias] = r.returns_array?
    1263:           eager_graph[:cartesian_product_number] += r[:cartesian_product_number] || 2
    1264:           ds = ds.eager_graph_associations(ds, r.associated_class, assoc_table_alias, requirements + [assoc_table_alias], *associations) unless associations.empty?
    1265:           ds
    1266:         end

eager_graph_associations(ds, model, ta, requirements, *associations)

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 1277
    1277:         def eager_graph_associations(ds, model, ta, requirements, *associations)
    1278:           return ds if associations.empty?
    1279:           associations.flatten.each do |association|
    1280:             ds = case association
    1281:             when Symbol
    1282:               ds.eager_graph_association(ds, model, ta, requirements, check_association(model, association))
    1283:             when Hash
    1284:               association.each do |assoc, assoc_assocs|
    1285:                 ds = ds.eager_graph_association(ds, model, ta, requirements, check_association(model, assoc), assoc_assocs)
    1286:               end
    1287:               ds
    1288:             else raise(Sequel::Error, 'Associations must be in the form of a symbol or hash')
    1289:             end
    1290:           end
    1291:           ds
    1292:         end

eager_graph_build_associations(record_graphs)

Build associations out of the array of returned object graphs.

[Source]

          # File lib/sequel/model/associations.rb, line 1295
    1295:         def eager_graph_build_associations(record_graphs)
    1296:           eager_graph = @opts[:eager_graph]
    1297:           master = eager_graph[:master]
    1298:           requirements = eager_graph[:requirements]
    1299:           alias_map = eager_graph[:alias_association_name_map]
    1300:           type_map = eager_graph[:alias_association_type_map]
    1301:           reciprocal_map = eager_graph[:reciprocals]
    1302:
    1303:           # Make dependency map hash out of requirements array for each association.
    1304:           # This builds a tree of dependencies that will be used for recursion
    1305:           # to ensure that all parts of the object graph are loaded into the
    1306:           # appropriate subordinate association.
    1307:           dependency_map = {}
    1308:           # Sort the associations by requirements length, so that
    1309:           # requirements are added to the dependency hash before their
    1310:           # dependencies.
    1311:           requirements.sort_by{|a| a[1].length}.each do |ta, deps|
    1312:             if deps.empty?
    1313:               dependency_map[ta] = {}
    1314:             else
    1315:               deps = deps.dup
    1316:               hash = dependency_map[deps.shift]
    1317:               deps.each do |dep|
    1318:                 hash = hash[dep]
    1319:               end
    1320:               hash[ta] = {}
    1321:             end
    1322:           end
    1323:
    1324:           # This mapping is used to make sure that duplicate entries in the
    1325:           # result set are mapped to a single record.  For example, using a
    1326:           # single one_to_many association with 10 associated records,
    1327:           # the main object will appear in the object graph 10 times.
    1328:           # We map by primary key, if available, or by the object's entire values,
    1329:           # if not. The mapping must be per table, so create sub maps for each table
    1330:           # alias.
    1331:           records_map = {master=>{}}
    1332:           alias_map.keys.each{|ta| records_map[ta] = {}}
    1333:
    1334:           # This will hold the final record set that we will be replacing the object graph with.
    1335:           records = []
    1336:           record_graphs.each do |record_graph|
    1337:             primary_record = record_graph[master]
    1338:             key = primary_record.pk_or_nil || primary_record.values.sort_by{|x| x[0].to_s}
    1339:             if cached_pr = records_map[master][key]
    1340:               primary_record = cached_pr
    1341:             else
    1342:               records_map[master][key] = primary_record
    1343:               # Only add it to the list of records to return if it is a new record
    1344:               records.push(primary_record)
    1345:             end
    1346:             # Build all associations for the current object and it's dependencies
    1347:             eager_graph_build_associations_graph(dependency_map, alias_map, type_map, reciprocal_map, records_map, primary_record, record_graph)
    1348:           end
    1349:
    1350:           # Remove duplicate records from all associations if this graph could possibly be a cartesian product
    1351:           eager_graph_make_associations_unique(records, dependency_map, alias_map, type_map) if eager_graph[:cartesian_product_number] > 1
    1352:
    1353:           # Replace the array of object graphs with an array of model objects
    1354:           record_graphs.replace(records)
    1355:         end

eager_unique_table_alias(ds, table_alias)

Creates a unique table alias that hasn‘t already been used in the query. Will either be the table_alias itself or table_alias_N for some integer N (starting at 0 and increasing until an unused one is found).

[Source]

          # File lib/sequel/model/associations.rb, line 1360
    1360:         def eager_unique_table_alias(ds, table_alias)
    1361:           used_aliases = ds.opts[:from]
    1362:           used_aliases += ds.opts[:join].map{|j| j.table_alias || j.table} if ds.opts[:join]
    1363:           graph = ds.opts[:graph]
    1364:           used_aliases += graph[:table_aliases].keys if graph
    1365:           if used_aliases.include?(table_alias)
    1366:             i = 0
    1367:             loop do
    1368:               ta = "#{table_alias}_#{i}""#{table_alias}_#{i}"
    1369:               return ta unless used_aliases.include?(ta)
    1370:               i += 1
    1371:             end
    1372:           end
    1373:           table_alias
    1374:         end

[Validate]