dataset_source_alias.rb

lib/sequel/extensions/dataset_source_alias.rb
Last Update: 2016-02-11 15:50:14 -0800

The dataset_source_alias extension changes Sequel’s default behavior of automatically aliasing datasets from using t1, t2, etc. to using an alias based on the source of the dataset. Example:

DB.from(DB.from(:a))
# default: SELECT * FROM (SELECT * FROM a) AS t1
# with extension: SELECT * FROM (SELECT * FROM a) AS a

This also works when joining:

DB[:a].join(DB[:b], [:id])
# SELECT * FROM a INNER JOIN (SELECT * FROM b) AS b USING (id)

To avoid conflicting aliases, this attempts to alias tables uniquely if it detects a conflict:

DB.from(:a, DB.from(:a))
# SELECT * FROM a, (SELECT * FROM a) AS a_0

Note that not all conflicts are correctly detected and handled. It is encouraged to alias your datasets manually instead of relying on the auto-aliasing if there would be a conflict.

In the places where Sequel cannot determine the appropriate alias to use for the dataset, it will fallback to the standard t1, t2, etc. aliasing.

You can load this extension into specific datasets:

ds = DB[:table]
ds = ds.extension(:dataset_source_alias)

Or you can load it into all of a database’s datasets, which is probably the desired behavior if you are using this extension:

DB.extension(:dataset_source_alias)

Related module: Sequel::Dataset::DatasetSourceAlias