The Sequel Console

Sequel includes an IRB console for quick access to databases. You can use
it like this:

sequel sqlite://test.db # test.db in current directory

You get an IRB session with the database object stored in DB.

An Introduction

Sequel is designed to take the hassle away from connecting to databases and
manipulating them. Sequel deals with all the boring stuff like maintaining
connections, formatting SQL correctly and fetching records so you can
concentrate on your application.

Sequel uses the concept of datasets to retrieve data. A Dataset object
encapsulates an SQL query and supports chainability, letting you fetch data
using a convenient Ruby DSL that is both concise and flexible.

For example, the following one-liner returns the average GDP for countries
in the middle east region:

DB[:countries].filter(:region => 'Middle East').avg(:GDP)

Which is equivalent to:

SELECT avg(GDP) FROM countries WHERE region = 'Middle East'

Since datasets retrieve records only when needed, they can be stored and
later reused. Records are fetched as hashes (or custom model objects), and
are accessed using an Enumerable interface:

Arbitrary SQL queries

dataset = DB['select id from items']
dataset.count # will return the number of records in the result set
dataset.map(:id) # will return an array containing all values of the id column in the result set

You can also fetch records with raw SQL through the dataset:

DB['select * from items'].each do |row|
p row
end

You can use placeholders in your SQL string as well:

name = 'Jim'
DB['select * from items where name = ?', name].each do |row|
p row
end

Getting Dataset Instances

Datasets are the primary way records are retrieved and manipulated. They
are generally created via the Database#from or Database#[] methods:

posts = DB.from(:posts)
posts = DB[:posts] # same

Datasets will only fetch records when you tell them to. They can be
manipulated to filter records, change ordering, join tables, etc..

Retrieving Records

You can retrieve all records by using the all method:

posts.all

The all method returns an array of hashes, where each hash corresponds to a
record.

An aside: column references in Sequel

Sequel expects column names to be specified using symbols. In addition,
returned hashes always use symbols as their keys. This allows you to freely
mix literal values and column references. For example, the two following
lines produce equivalent SQL:

Model instances

Model instance are identified by a primary key. By default, Sequel assumes
the primary key column to be :id, unless it can get the primary key
information from the database. The Model.[] method can be used to fetch
records by their primary key:

post = Post[123]

The Model#pk method is used to retrieve the record's primary key value:

post.pk #=> 123

Sequel models allow you to use any column as a primary key, and even
composite keys made from multiple columns:

Iterating over records

A model class lets you iterate over subsets of records by proxying many
methods to the underlying dataset. This means that you can use most of the
Dataset API to create customized queries that return model instances, e.g.:

Note the use of super if you define your own hook methods. Almost all
Sequel::Model class and instance methods (not just hook methods) can be
overridden safely, but you have to make sure to call super when doing so,
otherwise you risk breaking things.

For the example above, you should probably use a database trigger if you
can. Hooks can be used for data integrity, but they will only enforce that
integrity when you are using the model. If you plan on allowing any other
access to the database, it's best to use database triggers for data
integrity.

Deleting records

You can delete individual records by calling #delete or #destroy. The only
difference between the two methods is that #destroy invokes before_destroy
and after_destroy hook methods, while #delete does not:

post.delete #=> bypasses hooks
post.destroy #=> runs hooks

Records can also be deleted en-masse by invoking Model.delete and
Model.destroy. As stated above, you can specify filters for the deleted
records:

one_to_many and many_to_many create a getter method, a method for adding an
object to the association, a method for removing an object from the
association, and a method for removing all associated objects from the
association:

All associations add a dataset method that can be used to further filter or
reorder the returned objects, or modify all of them:

# Delete all of this post's comments from the database
post.comments_dataset.destroy
# Return all tags related to this post with no subscribers, ordered by the tag's name
post.tags_dataset.filter(:subscribers=>0).order(:name).all

Eager Loading

Associations can be eagerly loaded via .eager and the :eager association
option. Eager loading is used when loading a group of objects. It loads all
associated objects for all of the current objects in one query, instead of
using a separate query to get the associated objects for each current
object. Eager loading requires that you retrieve all model objects at once
via .all (instead of individually by .each). Eager loading can be cascaded,
loading association's associated objects.

In addition to using eager, you can also use eager_graph, which will use a
single query to get the object and all associated objects. This may be
necessary if you want to filter or order the result set based on columns in
associated tables. It works with cascading as well, the syntax is exactly
the same. Note that using eager_graph to eagerly load multiple *_to_many
associations will cause the result set to be a cartesian product, so you
should be very careful with your filters when using it in that case.

Extending the underlying dataset

The obvious way to add table-wide logic is to define class methods to the
model class definition. That way you can define subsets of the underlying
dataset, change the ordering, or perform actions on multiple records:

Model Validations

You can define a validate method for your model, which #save will check
before attempting to save the model in the database. If an attribute of the
model isn't valid, you should add a error message for that attribute to
the model object's errors. If an object has any errors added by the
validate method, save will raise an error or return false depending on how
it is configured.

class Post < Sequel::Model
def validate
errors.add(:name, "can't be empty") if name.empty?
errors.add(:written_on, "should be in the past") if written_on >= Time.now
end
end