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
Add the eager! and eager_graph! mutation methods to the dataset.
# File lib/sequel/model/associations.rb, line 1240 1240: def self.extended(obj) 1241: obj.def_mutation_method(:eager, :eager_graph) 1242: 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 *_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.
# File lib/sequel/model/associations.rb, line 1270 1270: def eager(*associations) 1271: opt = @opts[:eager] 1272: opt = opt ? opt.dup : {} 1273: associations.flatten.each do |association| 1274: case association 1275: when Symbol 1276: check_association(model, association) 1277: opt[association] = nil 1278: when Hash 1279: association.keys.each{|assoc| check_association(model, assoc)} 1280: opt.merge!(association) 1281: else raise(Sequel::Error, 'Associations must be in the form of a symbol or hash') 1282: end 1283: end 1284: clone(:eager=>opt) 1285: end
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).
# File lib/sequel/model/associations.rb, line 1307 1307: def eager_graph(*associations) 1308: ds = if @opts[:eager_graph] 1309: self 1310: else 1311: # Each of the following have a symbol key for the table alias, with the following values: 1312: # :reciprocals - the reciprocal instance variable to use for this association 1313: # :requirements - array of requirements for this association 1314: # :alias_association_type_map - the type of association for this association 1315: # :alias_association_name_map - the name of the association for this association 1316: clone(:eager_graph=>{:requirements=>{}, :master=>alias_symbol(first_source), :alias_association_type_map=>{}, :alias_association_name_map=>{}, :reciprocals=>{}, :cartesian_product_number=>0}) 1317: end 1318: ds.eager_graph_associations(ds, model, ds.opts[:eager_graph][:master], [], *associations) 1319: 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.
# File lib/sequel/model/associations.rb, line 1325 1325: def ungraphed 1326: super.clone(:eager_graph=>nil) 1327: end
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:
# File lib/sequel/model/associations.rb, line 1343 1343: def eager_graph_association(ds, model, ta, requirements, r, *associations) 1344: klass = r.associated_class 1345: assoc_name = r[:name] 1346: assoc_table_alias = ds.unused_table_alias(assoc_name) 1347: ds = r[:eager_grapher].call(ds, assoc_table_alias, ta) 1348: ds = ds.order_more(*qualified_expression(r[:order], assoc_table_alias)) if r[:order] and r[:order_eager_graph] 1349: eager_graph = ds.opts[:eager_graph] 1350: eager_graph[:requirements][assoc_table_alias] = requirements.dup 1351: eager_graph[:alias_association_name_map][assoc_table_alias] = assoc_name 1352: eager_graph[:alias_association_type_map][assoc_table_alias] = r.returns_array? 1353: eager_graph[:cartesian_product_number] += r[:cartesian_product_number] || 2 1354: ds = ds.eager_graph_associations(ds, r.associated_class, assoc_table_alias, requirements + [assoc_table_alias], *associations) unless associations.empty? 1355: ds 1356: end
Check the associations are valid for the given model. Call eager_graph_association on each association.
Arguments:
# File lib/sequel/model/associations.rb, line 1367 1367: def eager_graph_associations(ds, model, ta, requirements, *associations) 1368: return ds if associations.empty? 1369: associations.flatten.each do |association| 1370: ds = case association 1371: when Symbol 1372: ds.eager_graph_association(ds, model, ta, requirements, check_association(model, association)) 1373: when Hash 1374: association.each do |assoc, assoc_assocs| 1375: ds = ds.eager_graph_association(ds, model, ta, requirements, check_association(model, assoc), assoc_assocs) 1376: end 1377: ds 1378: else raise(Sequel::Error, 'Associations must be in the form of a symbol or hash') 1379: end 1380: end 1381: ds 1382: end
Build associations out of the array of returned object graphs.
# File lib/sequel/model/associations.rb, line 1385 1385: def eager_graph_build_associations(record_graphs) 1386: eager_graph = @opts[:eager_graph] 1387: master = eager_graph[:master] 1388: requirements = eager_graph[:requirements] 1389: alias_map = eager_graph[:alias_association_name_map] 1390: type_map = eager_graph[:alias_association_type_map] 1391: reciprocal_map = eager_graph[:reciprocals] 1392: 1393: # Make dependency map hash out of requirements array for each association. 1394: # This builds a tree of dependencies that will be used for recursion 1395: # to ensure that all parts of the object graph are loaded into the 1396: # appropriate subordinate association. 1397: dependency_map = {} 1398: # Sort the associations by requirements length, so that 1399: # requirements are added to the dependency hash before their 1400: # dependencies. 1401: requirements.sort_by{|a| a[1].length}.each do |ta, deps| 1402: if deps.empty? 1403: dependency_map[ta] = {} 1404: else 1405: deps = deps.dup 1406: hash = dependency_map[deps.shift] 1407: deps.each do |dep| 1408: hash = hash[dep] 1409: end 1410: hash[ta] = {} 1411: end 1412: end 1413: 1414: # This mapping is used to make sure that duplicate entries in the 1415: # result set are mapped to a single record. For example, using a 1416: # single one_to_many association with 10 associated records, 1417: # the main object will appear in the object graph 10 times. 1418: # We map by primary key, if available, or by the object's entire values, 1419: # if not. The mapping must be per table, so create sub maps for each table 1420: # alias. 1421: records_map = {master=>{}} 1422: alias_map.keys.each{|ta| records_map[ta] = {}} 1423: 1424: # This will hold the final record set that we will be replacing the object graph with. 1425: records = [] 1426: record_graphs.each do |record_graph| 1427: primary_record = record_graph[master] 1428: key = primary_record.pk_or_nil || primary_record.values.sort_by{|x| x[0].to_s} 1429: if cached_pr = records_map[master][key] 1430: primary_record = cached_pr 1431: else 1432: records_map[master][key] = primary_record 1433: # Only add it to the list of records to return if it is a new record 1434: records.push(primary_record) 1435: end 1436: # Build all associations for the current object and it's dependencies 1437: eager_graph_build_associations_graph(dependency_map, alias_map, type_map, reciprocal_map, records_map, primary_record, record_graph) 1438: end 1439: 1440: # Remove duplicate records from all associations if this graph could possibly be a cartesian product 1441: eager_graph_make_associations_unique(records, dependency_map, alias_map, type_map) if eager_graph[:cartesian_product_number] > 1 1442: 1443: # Replace the array of object graphs with an array of model objects 1444: record_graphs.replace(records) 1445: end