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 can be 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
Add the eager! and eager_graph! mutation methods to the dataset.
# File lib/sequel/model/associations.rb, line 1264 1264: def self.extended(obj) 1265: obj.def_mutation_method(:eager, :eager_graph) 1266: 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. 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 1294 1294: def eager(*associations) 1295: opt = @opts[:eager] 1296: opt = opt ? opt.dup : {} 1297: associations.flatten.each do |association| 1298: case association 1299: when Symbol 1300: check_association(model, association) 1301: opt[association] = nil 1302: when Hash 1303: association.keys.each{|assoc| check_association(model, assoc)} 1304: opt.merge!(association) 1305: else raise(Sequel::Error, 'Associations must be in the form of a symbol or hash') 1306: end 1307: end 1308: clone(:eager=>opt) 1309: 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 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 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 definied, is respected. eager_graph probably won‘t work correctly on a limited dataset, unless you are only graphing many_to_one and one_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 table alias symbol keys and model object values).
# File lib/sequel/model/associations.rb, line 1332 1332: def eager_graph(*associations) 1333: ds = if @opts[:eager_graph] 1334: self 1335: else 1336: # Each of the following have a symbol key for the table alias, with the following values: 1337: # :reciprocals - the reciprocal instance variable to use for this association 1338: # :requirements - array of requirements for this association 1339: # :alias_association_type_map - the type of association for this association 1340: # :alias_association_name_map - the name of the association for this association 1341: clone(:eager_graph=>{:requirements=>{}, :master=>alias_symbol(first_source), :alias_association_type_map=>{}, :alias_association_name_map=>{}, :reciprocals=>{}, :cartesian_product_number=>0}) 1342: end 1343: ds.eager_graph_associations(ds, model, ds.opts[:eager_graph][:master], [], *associations) 1344: 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 1350 1350: def ungraphed 1351: super.clone(:eager_graph=>nil) 1352: 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:
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 |
# File lib/sequel/model/associations.rb, line 1368 1368: def eager_graph_association(ds, model, ta, requirements, r, *associations) 1369: klass = r.associated_class 1370: assoc_name = r[:name] 1371: assoc_table_alias = ds.unused_table_alias(assoc_name) 1372: ds = r[:eager_grapher].call(ds, assoc_table_alias, ta) 1373: ds = ds.order_more(*qualified_expression(r[:order], assoc_table_alias)) if r[:order] and r[:order_eager_graph] 1374: eager_graph = ds.opts[:eager_graph] 1375: eager_graph[:requirements][assoc_table_alias] = requirements.dup 1376: eager_graph[:alias_association_name_map][assoc_table_alias] = assoc_name 1377: eager_graph[:alias_association_type_map][assoc_table_alias] = r.returns_array? 1378: eager_graph[:cartesian_product_number] += r[:cartesian_product_number] || 2 1379: ds = ds.eager_graph_associations(ds, r.associated_class, assoc_table_alias, requirements + [assoc_table_alias], *associations) unless associations.empty? 1380: ds 1381: 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 |
# File lib/sequel/model/associations.rb, line 1392 1392: def eager_graph_associations(ds, model, ta, requirements, *associations) 1393: return ds if associations.empty? 1394: associations.flatten.each do |association| 1395: ds = case association 1396: when Symbol 1397: ds.eager_graph_association(ds, model, ta, requirements, check_association(model, association)) 1398: when Hash 1399: association.each do |assoc, assoc_assocs| 1400: ds = ds.eager_graph_association(ds, model, ta, requirements, check_association(model, assoc), assoc_assocs) 1401: end 1402: ds 1403: else raise(Sequel::Error, 'Associations must be in the form of a symbol or hash') 1404: end 1405: end 1406: ds 1407: end
Build associations out of the array of returned object graphs.
# File lib/sequel/model/associations.rb, line 1410 1410: def eager_graph_build_associations(record_graphs) 1411: eager_graph = @opts[:eager_graph] 1412: master = eager_graph[:master] 1413: requirements = eager_graph[:requirements] 1414: alias_map = eager_graph[:alias_association_name_map] 1415: type_map = eager_graph[:alias_association_type_map] 1416: reciprocal_map = eager_graph[:reciprocals] 1417: 1418: # Make dependency map hash out of requirements array for each association. 1419: # This builds a tree of dependencies that will be used for recursion 1420: # to ensure that all parts of the object graph are loaded into the 1421: # appropriate subordinate association. 1422: dependency_map = {} 1423: # Sort the associations by requirements length, so that 1424: # requirements are added to the dependency hash before their 1425: # dependencies. 1426: requirements.sort_by{|a| a[1].length}.each do |ta, deps| 1427: if deps.empty? 1428: dependency_map[ta] = {} 1429: else 1430: deps = deps.dup 1431: hash = dependency_map[deps.shift] 1432: deps.each do |dep| 1433: hash = hash[dep] 1434: end 1435: hash[ta] = {} 1436: end 1437: end 1438: 1439: # This mapping is used to make sure that duplicate entries in the 1440: # result set are mapped to a single record. For example, using a 1441: # single one_to_many association with 10 associated records, 1442: # the main object will appear in the object graph 10 times. 1443: # We map by primary key, if available, or by the object's entire values, 1444: # if not. The mapping must be per table, so create sub maps for each table 1445: # alias. 1446: records_map = {master=>{}} 1447: alias_map.keys.each{|ta| records_map[ta] = {}} 1448: 1449: # This will hold the final record set that we will be replacing the object graph with. 1450: records = [] 1451: record_graphs.each do |record_graph| 1452: primary_record = record_graph[master] 1453: key = primary_record.pk_or_nil || primary_record.values.sort_by{|x| x[0].to_s} 1454: if cached_pr = records_map[master][key] 1455: primary_record = cached_pr 1456: else 1457: records_map[master][key] = primary_record 1458: # Only add it to the list of records to return if it is a new record 1459: records.push(primary_record) 1460: end 1461: # Build all associations for the current object and it's dependencies 1462: eager_graph_build_associations_graph(dependency_map, alias_map, type_map, reciprocal_map, records_map, primary_record, record_graph) 1463: end 1464: 1465: # Remove duplicate records from all associations if this graph could possibly be a cartesian product 1466: eager_graph_make_associations_unique(records, dependency_map, alias_map, type_map) if eager_graph[:cartesian_product_number] > 1 1467: 1468: # Replace the array of object graphs with an array of model objects 1469: record_graphs.replace(records) 1470: end