Skip to content


Subversion checkout URL

You can clone with
Download ZIP
Sequel: The Database Toolkit for Ruby
Ruby Other

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.


== Sequel: The Database Toolkit for Ruby

Sequel is a lightweight database access toolkit for Ruby.

* Sequel provides thread safety, connection pooling and a concise DSL
  for constructing database queries and table schemas.
* Sequel also includes a lightweight but comprehensive ORM layer for
  mapping records to Ruby objects and handling associated records.
* Sequel supports advanced database features such as prepared statements,
  bound variables, master/slave configurations, and database sharding.
* Sequel makes it easy to deal with multiple records without having
  to break your teeth on SQL.
* Sequel currently has adapters for ADO, DB2, DBI, Informix, JDBC,
  MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3.

== Resources

* {Website}[]
* {Source code}[]
* {Bug tracking}[]
* {Google group}[]
* {RDoc}[]

To check out the source code:
  git clone git://
=== Contact


== Installation

  sudo gem install sequel
== A Short Example

  require 'rubygems'
  require 'sequel'
  DB = Sequel.sqlite # memory database
  DB.create_table :items do # Create a new table
    column :name, :text
    column :price, :float
  items = DB[:items] # Create a dataset
  # Populate the table
  items << {:name => 'abc', :price => rand * 100}
  items << {:name => 'def', :price => rand * 100}
  items << {:name => 'ghi', :price => rand * 100}
  # Print out the number of records
  puts "Item count: #{items.count}"
  # Print out the records in descending order by price
  # Print out the average price

== The Sequel Console

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

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


== An Introduction



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

  DB[:countries].filter(:region => 'Middle East').reverse_order(:area).limit(5).avg(:GDP)
Which is equivalent to:

  SELECT avg(GDP) FROM countries WHERE region = 'Middle East' ORDER BY area DESC LIMIT 5

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



== Getting Started

=== Connecting to a database


  require 'sequel'
  DB = Sequel.connect('sqlite://blog.db')



    :max_connections => 10, :loggers => ['log/db.log']))



=== Arbitrary SQL queries

  DB.execute("create table t (a text, b text)")
  DB.execute("insert into t values ('a', 'b')")

Or more succinctly:

  DB << "create table t (a text, b text)"
  DB << "insert into t values ('a', 'b')"

You can also create datasets based on raw SQL:

  dataset = DB['select * from items']

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

    p row

=== Getting Dataset Instances

Dataset is the primary means through which records are retrieved and manipulated. You can create an blank dataset by using the dataset method:

  dataset = DB.dataset

Or by using the from methods:

  posts = DB.from(:posts)

The recommended way is the equivalent shorthand:

  posts = DB[:posts]

Datasets will only fetch records when you explicitly ask for them. Datasets can be manipulated to filter through records, change record order, join tables, etc..

=== Retrieving Records

You can retrieve records by using the all method:



You can also iterate through records one at a time:

  posts.each{|row| p row}

Or perform more advanced stuff:
  posts.inject({}){|h, r| h[r[:id]] = r[:name]}
You can also retrieve the first record in a dataset:

Or retrieve a single record with a specific value:

  posts[:id => 1]

=== Filtering Records

The simplest way to filter records is to provide a hash of values to match:

You can also specify ranges:

Or lists of values:

Sequel also accepts expressions:
  my_posts = posts.filter(:stamp > << 1)
Some adapters (like postgresql) will also let you specify Regexps:

You can also use an inverse filter:

  my_posts = posts.filter(:category => /ruby/i).invert # same as above

You can also specify a custom WHERE clause using a string:

  posts.filter('stamp IS NOT NULL')

You can use parameters in your string, as well (ActiveRecord style):

  posts.filter((:stamp < - 3) & ~(:author => author_name)) # same as above

Datasets can also be used as subqueries:

  DB[:items].filter('price > ?', DB[:items].select('AVG(price) + 100'))


  my_posts.each{|row| p row}
See the doc/dataset_filtering.rdoc file for more details.

=== Summarizing Records

Counting records is easy:

And you can also query maximum/minimum values:
  max_value = DB[:history].max(:value)
Or calculate a sum:
  total = DB[:items].sum(:price)
=== Ordering Records

Ordering datasets is simple:

  posts.order(:stamp) # ORDER BY stamp
  posts.order(:stamp, :name) # ORDER BY stamp, name
You can also specify descending order

  posts.order(:stamp.desc) # ORDER BY stamp DESC

=== Deleting Records

Deleting records from the table is done with delete:

=== Inserting Records

Inserting records into the table is done with insert:

  posts << {:category => 'ruby', :author => 'david'} # same as above
=== Updating Records

Updating records in the table is done with update:


=== Joining Tables

Joining is very useful in a variety of scenarios, for example many-to-many relationships. With Sequel it's really easy:

    filter(:order_items__order_id => 1234)
This is equivalent to the SQL:

  SELECT * FROM items LEFT OUTER JOIN order_items
  ON order_items.item_id = 
  WHERE order_items.order_id = 1234

You can then do anything you like with the dataset:

  order_total = order_items.sum(:price)
Which is equivalent to the SQL:

  SELECT sum(price) FROM items LEFT OUTER JOIN order_items
  ON order_items.item_id =
  WHERE order_items.order_id = 1234
=== Graphing Datasets


  => {:id=>(could be or, :item_id=>order_items.order_id}



== Sequel Models

Models in Sequel are based on the Active Record pattern described by Martin Fowler ( A model class corresponds to a table or a dataset, and an instance of that class wraps a single record in the model's underlying dataset.

Model classes are defined as regular Ruby classes:

  DB = Sequel.connect('sqlite:/blog.db')
  class Post < Sequel::Model


  Post.table_name #=> :posts


  class Post < Sequel::Model(:my_posts)
  # or:
  Post.set_dataset :my_posts
  # or:
  Post.set_dataset DB[:my_posts].where(:category => 'ruby')

=== Model instances

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

  post = Post[123]



  class Post < Sequel::Model
    set_primary_key [:category, :title]


You can also define a model class that does not have a primary key, but then you lose the ability to update records.

A model instance can also be fetched by specifying a condition:

  post = Post.find(:num_comments < 10)

=== Iterating over records

A model class lets you iterate over specific records by acting as a proxy to the underlying dataset. This means that you can use the entire Dataset API to create customized queries that return model instances, e.g.:


You can also manipulate the records in the dataset:

  Post.filter(:num_comments < 7).delete
  Post.filter( => 'ruby')

=== Accessing record values

A model instances stores its values as a hash:


You can read the record values as object attributes (assuming the attribute names are valid columns in the model's dataset): #=> 123
  post.title #=> 'hello world'

You can also change record values:

  post.title = 'hey there'

Another way to change values by using the #update_with_params method:

  post.update_with_params(:title => 'hey there')

=== Creating new records

New records can be created by calling Model.create:


Another way is to construct a new instance and save it:

  post =
  post.title = 'hello world'

You can also supply a block to and Model.create:


  post = do |p|
    p.title = 'hello world'

=== Hooks

You can execute custom code when creating, updating, or deleting records by using hooks. The before_create and after_create hooks wrap record creation. The before_update and after_update wrap record updating. The before_save and after_save wrap record creation and updating. The before_destroy and after_destroy wrap destruction. The before_validation and after_validation hooks wrap validation.

Hooks are defined by supplying a block:

  class Post < Sequel::Model
    after_create do

    after_destroy do

=== 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 hooks, while #delete does not:

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



Please note that if Model.destroy is called, each record is deleted 
separately, but Model.delete deletes all relevant records with a single 
SQL statement.

=== Associations

Associations are used in order to specify relationships between model classes that reflect relations between tables in the database using foreign keys.

  class Post < Sequel::Model
    many_to_one :author
    one_to_many :comments
    many_to_many :tags

You can also use the ActiveRecord names for these associations:

  class Post < Sequel::Model
    belongs_to :author
    has_many :comments
    has_and_belongs_to_many :tags

many_to_one creates a getter and setter for each model object:

  class Post < Sequel::Model
    many_to_one :author



  class Post < Sequel::Model
    one_to_many :comments
    many_to_many :tags

  comment = Comment.create(:text=>'hi')
  tag = Tag.create(:tag=>'interesting')

=== Eager Loading


  class Person < Sequel::Model
    one_to_many :posts, :eager=>[:tags]

  class Post < Sequel::Model
    many_to_one :person
    one_to_many :replies
    many_to_many :tags

  class Tag < Sequel::Model
    many_to_many :posts
    many_to_many :replies

  class Reply < Sequel::Model
    many_to_one :person
    many_to_one :post
    many_to_many :tags

  # Eager loading via .eager

  Post.filter(:topic > 'M').order(:date).limit(5).eager(:person).all
  person = Person.first
  # These are equivalent
  Post.eager(:person, :tags).all
  # Cascading via .eager

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 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.

=== Caching model instances with memcached

Sequel models can be cached using memcached based on their primary keys. The use of memcached can significantly reduce database load by keeping model instances in memory. The set_cache method is used to specify caching:

  require 'memcache'
  CACHE = 'localhost:11211', :namespace => 'blog'

  class Author < Sequel::Model
    set_cache CACHE, :ttl => 3600

  Author[333] # database hit
  Author[333] # cache hit

=== Extending the underlying dataset


  class Post < Sequel::Model
    def self.posts_with_few_comments
      filter(:num_comments < 30)

    def self.clean_posts_with_few_comments


  class Post < Sequel::Model
    def_dataset_method(:posts_with_few_comments) do
      filter(:num_comments < 30)

    def_dataset_method(:clean_posts_with_few_comments) do


  Post.filter(:category => 'ruby').clean_old_posts

Sequel models also provide a short hand notation for filters:

  class Post < Sequel::Model
    subset(:posts_with_few_comments, :num_comments < 30)
    subset :invisible, :visible => false

=== Defining the underlying schema

Model classes can also be used as a place to define your table schema and control it. The schema DSL is exactly the same provided by Sequel::Schema::Generator:

  class Post < Sequel::Model
    set_schema do
      primary_key :id
      text :title
      text :category
      foreign_key :author_id, :table => :authors

You can then create the underlying table, drop it, or recreate it:

  Post.create_table! # drops the table if it exists and then recreates it

=== Basic Model Validations

To assign default validations to a sequel model:

  class MyModel < Sequel::Model
    validates do

You may also perform the usual 'longhand' way to assign default model validates directly within the model class itself:

  class MyModel < Sequel::Model
Something went wrong with that request. Please try again.