Sequel Hybrid Table Inheritance
This is a sequel plugin that combines the functionality of the single and class table inheritance plugins. This plugin uses the single_table_inheritance plugin and should work as a drop in replacement for the class_table_inheritance plugins. This allows using new tables for subclasses only when need for additional columns or possibly referential integrity to exclusively subclassed rows.
Additional features over the class table inheritance plugin
For class table inheritance use this provides additional functionality beyond the standard class table inheritance plugin including the following:
-
Eager loading in addition to lazy loading of subclasses
-
Use RETURNING * on insert if available avoiding a select query after new model saves
-
Features found in the single table inheritance not in class table inheritance Notably the key_map, key_chooser options and accepting a proc in addition to a hash for model_map option
Documentation
Overview
The hybrid_table_inheritance pluging allows model subclasses to be stored in either the same table as the parent model or a different table with a key referencing the parent table. This combines the functionality of single and class (multiple) table inheritance into one plugin. This plugin uses the single_table_inheritance plugin and should work as a drop in replacement for the class_table_inheritance plugins. This allows introducing new tables only when needed typically for additional fields or possibly referential integrity to subclassed objects.
Detail
For example, with this hierarchy:
Employee
/ \
Staff Manager
| |
Cook Executive
|
CEO
the following database schema may be used (table - columns):
- employees
-
id, name, kind
- staff
-
id, manager_id
- managers
-
id, num_staff
- executives
-
id, num_managers
The hybrid_table_inheritance plugin assumes that the root table (e.g. employees) has a primary key field (usually autoincrementing), and all other tables have a foreign key of the same name that points to the same key in their superclass’s table. In this example, the employees id column is a primary key and the id column in every other table is a foreign key referencing the employees id.
In this example the employees table stores Staff model objects and the executives table stores CEO model objects.
When using the class_table_inheritance plugin, subclasses use joined datasets:
Employee.dataset.sql
# SELECT * FROM employees
Manager.dataset.sql
# SELECT employees.id, employees.name, employees.kind,
# managers.num_staff
# FROM employees
# JOIN managers ON (managers.id = employees.id)
CEO.dataset.sql
# SELECT employees.id, employees.name, employees.kind,
# managers.num_staff, executives.num_managers
# FROM employees
# JOIN managers ON (managers.id = employees.id)
# JOIN executives ON (executives.id = managers.id)
# WHERE (employees.kind IN ('CEO'))
This allows CEO.all to return instances with all attributes loaded. The plugin overrides the deleting, inserting, and updating in the model to work with multiple tables, by handling each table individually.
Subclass loading
When model objects are retrieved for a superclass the result could be subclass objects needing additional attributes from other tables. This plugin can load those additional attributes immediately with eager loading or when requested on the object with lazy loading.
With eager loading, the additional needed rows will be loaded with the all or first methods. Note that eager loading does not work with the each method because all of the records must be loaded to determine the keys for each subclass query. In that case lazy loading can be used or the each method used on the result of the all method.
If lazy loading is used the lazy_attributes plugin will be included to return subclass specific attributes that were not loaded when calling superclass methods (since those wouldn’t join to the subclass tables). For example:
a = Employee.all # [<#Staff>, <#Manager>, <#Executive>]
a.first.values # {:id=>1, name=>'S', :kind=>'Staff'}
a.first.manager_id # Loads the manager_id attribute from the database
If you want to get all columns in a subclass instance after loading via the superclass, call Model#refresh.
a = Employee.first
a.values # {:id=>1, name=>'S', :kind=>'CEO'}
a.refresh.values # {:id=>1, name=>'S', :kind=>'Executive', :num_staff=>4, :num_managers=>2}
The option :subclass_load sets the default subclass loading strategy. It accepts :eager, :eager_only, :lazy or :lazy_only with a default of :lazy The _only options will only allow that strategy to be used. In addition eager or lazy can be called on a dataset to override the default strategy used assuming an _only option was not set.
Usage
# Use the default of storing the class name in the sti_key
# column (:kind in this case)
class Employee < Sequel::Model
plugin :hybrid_table_inheritance, :key=>:kind
end
# Have subclasses inherit from the appropriate class
class Staff < Employee; end # uses staff table
class Cook < Staff; end # cooks table doesn't exist so uses staff table
class Manager < Employee; end # uses managers table
class Executive < Manager; end # uses executives table
class CEO < Executive; end # ceos table doesn't exist so uses executives table
# Some examples of using these options:
# Specifying the tables with a :table_map hash
Employee.plugin :hybrid_table_inheritance,
:table_map=>{:Employee => :employees,
:Staff => :staff,
:Cook => :staff,
:Manager => :managers,
:Executive => :executives,
:CEO => :executives }
# Using integers to store the class type, with a :model_map hash
# and an sti_key of :type
Employee.plugin :hybrid_table_inheritance, :type,
:model_map=>{1=>:Staff, 2=>:Cook, 3=>:Manager, 4=>:Executive, 5=>:CEO}
# Using non-class name strings
Employee.plugin :hybrid_table_inheritance, :key=>:type,
:model_map=>{'staff'=>:Staff, 'cook staff'=>:Cook, 'supervisor'=>:Manager}
# By default the plugin sets the respective column value
# when a new instance is created.
Cook.create.type == 'cook staff'
Manager.create.type == 'supervisor'
# You can customize this behavior with the :key_chooser option.
# This is most useful when using a non-bijective mapping.
Employee.plugin :hybrid_table_inheritance, :key=>:type,
:model_map=>{'cook staff'=>:Cook, 'supervisor'=>:Manager},
:key_chooser=>proc{|instance| instance.model.sti_key_map[instance.model.to_s].first || 'stranger' }
# Using custom procs, with :model_map taking column values
# and yielding either a class, string, symbol, or nil,
# and :key_map taking a class object and returning the column
# value to use
Employee.plugin :single_table_inheritance, :key=>:type,
:model_map=>proc{|v| v.reverse},
:key_map=>proc{|klass| klass.name.reverse}
# You can use the same class for multiple values.
# This is mainly useful when the sti_key column contains multiple values
# which are different but do not require different code.
Employee.plugin :single_table_inheritance, :key=>:type,
:model_map=>{'staff' => "Staff",
'manager' => "Manager",
'overpayed staff' => "Staff",
'underpayed staff' => "Staff"}
One minor issue to note is that if you specify the :key_map option as a hash, instead of having it inferred from the :model_map, you should only use class name strings as keys, you should not use symbols as keys.
Options
- :key
-
column symbol that holds the key that identifies the class to use. Necessary if you want to call model methods on a superclass that return subclass instances
- :model_map
-
Hash or proc mapping the key column values to model class names.
- :key_map
-
Hash or proc mapping model class names to key column values. Each value or return is an array of possible key column values.
- :key_chooser
-
proc returning key for the provided model instance
- :table_map
-
Hash with class name symbols keys mapping to table name symbol values Overrides implicit table names
- :subclass_load
-
subclass loading strategy, defaults to :lazy options: :eager, :eager_only, :lazy or :lazy_only