DEV Community

Tori Crawford
Tori Crawford

Posted on

Sequel: An Alternative to ActiveRecord

On Friday, I was given a take home coding assessment. I was required to build a RESTful API with Ruby with one big catch: no Rails. A few take aways from this -

  1. I was super excited to even get the opportunity, because this is my second coding challenge of my job search. Practice makes perfect, so the more I get, the more confident and comfortable I’ll be the following time.

  2. I gained invaluable experience building with tools/frameworks I don’t know I would have every known existed and/or used. One of these tools was Sequel, which is what I’ll be writing about today.

For my challenge, I was required to use Sequel instead of ActiveRecord and boy was it a challenge. My opinion on Sequel is still up in the air. My first instinct was to wonder why anybody would ever use this gem over ActiveRecord. While working with it, I really enjoyed one aspect which softened my opinion a bit. We shall see what it is by the time I’ve finished this blog post.

What is Sequel?

Sequel is a Ruby gem that functions as a “simple, flexible, and powerful SQL database access toolkit.” In other words, it is comparable to the widely used ActiveRecord gem. Sequel allows you to run migrations, queries, and manipulate the database, just as ActiveRecord does.

Database Types Supported by Sequel

Sequel currently supports the following database types: ADO, Amalgalite, IBM_DB, JDBC, MySQL, Mysql2, ODBC, Oracle, PostreSQL, SQLAnywhere, SQLite3, and TinyTDS.

Installing Sequel

In order to use Sequel, you must first install the gem to your project. To do this, go to your Gemfile and add gem ‘sequel’. You will need to install the gem by running $ bundle install in your terminal.

Within your application.rb file, you will need to require ‘sequel’, just as you would with ActiveRecord.

Creating the Database

One thing that I found unique about Sequel (and of course I hit an error to figure it out), is that the database must first be created before you attempt to connect to connect Sequel to the database.

To create the database, run the following command (with your own database name) - $ createdb pets_development.

Note: For the purpose of this tutorial, I am using PostgresSQL. The creation of the database is a little unique compared to that of SQLite3, so please keep that in mind and visit this page if you are using a different type of database.

Creation of Migration Files

Creating the migration files is very similar to ActiveRecord in the layout, however, there isn’t a simple command to run like rake db:create. I created my migration files manually, but it is important to note that you should still include a timestamp to the beginning of your file name, as Sequel requires it.

# 20190514_dogs.rb
Sequel.migration do
  change do
    create_table(:dogs) do
      primary_key :id
      String :name, :null => false
      String :breed, :null => false
      foreign_key :owner_id, :people
    end
  end 
end 

# 20190514_owners.rb
Sequel.migration do
  change do
    create_table(:owners) do
      primary_key :id
      String :name, :null => false
    end
  end 
end

Connecting to the Database

Now that we have the database and the migration files created, we need to connect Sequel to the database. In order to do this, you need to navigate to your application.rb file and include the following code:

# application.rb

# establishes Sequel connection to db
DB = Sequel.connect(adapter: :postgres, database: pets_development', host: 'localhost')

Note: There are multiple ways to connect to the database, this is just the way I preferred. This article contains other options.

Another Note: You cannot connect to the database after creating your models, so please make sure to complete this connection step BEFORE creating your models (I learned this the hard way).

Creation of Models

Models in Sequel are set up very similarly to ActiveRecord.

# dog.rb 
class Dog < Sequel::Model
  many_to_one :person

  def validate
    super
    errors.add(:name, "must be present") if name.empty?
    errors.add(:breed, "must be present") if breed.empty?
  end
end

# owner.rb 
class Owner < Sequel::Model
  one_to_many :dogs

  def validate
    super
    errors.add(:name, "must be present") if name.empty?
  end
end

Running the Migrations

Now for our final step to getting our database set up, running our migrations. Unfortunately, running our migrations isn’t as easy as typing $ rake db:migrate as it is with ActiveRecord. Luckily enough though, we still have a command to do this. Run $ sequel -m db/migrate/ postgres://localhost/pets_development.

Note: The ‘db/migrate/’ is the path to my migration files, please replace this with your own.

Seeding the Database

I created seed files for this project so I am going to explain setting this up. The first thing we need to do is install a helpful gem, Sequel-Seed. Go to your Gemfile and add require ‘sequel-seed’ then run $ bundle install.

Next, we need to create our seeds files. Seeds files also need to have a timestamp at the beginning of the name.

# 20190514_dogs_seed.rb 
Sequel.seed do
  def run
    [
      [buddy, labrador, 1],
      [spot, golden retriever, 1],
      [princess, beagle, 2]
    ].each do |name, breed, owner_id|
      Dog.create name: name, breed: breed, owner_id: owner_id
    end
  end
end 

# 20190514_owners_seed.rb
Sequel.seed do
  def run
    [
      [angie],
      [bill],
    ].each do |name|
      Dog.create name: name
    end
  end
end

Go to your application.rb file and insert the following code to load the seed extension and seed the database:

# application.rb
require sequel/extensions/seed

# loads the extension
Sequel.extension :seed 

# seeds the database
Sequel::Seeder.apply(DB, db/seeds/)

Queries

Queries within Sequel are somewhat similar to those in ActiveRecord. Using Dog.all will return all dogs within the database. You can use .first and .last to get the first and last instances of an object in the database. .order allows you to order the instance within the database. You can use .where() to find all instances within the database that match the given object key. You can view more of these here.

Raw SQL Queries

One really neat thing about Sequel is that you can make raw SQL queries to the database. So, you can do something like this:

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

Final Thoughts

I really like the functionality of using raw SQL. I really like SQL queries and I always take advantage of getting to practice my SQL skills. This aspect of Sequel really changed my outlook on it. It really isn't all that different than ActiveRecord, but I still prefer using ActiveRecord. My reasoning for this is because of the rake db commands. They make life so much easier.

I do see Sequel as a great tool to use as an alternative to ActiveRecord, though. I hope that this post has peaked your curiosity and maybe intrigued you to try Sequel out.

Happy Coding!

Sources

Sequel: The Database Toolkit for Ruby
Getting Started with Sequel

Latest comments (7)

Collapse
 
janko profile image
Janko Marohnić • Edited

Very nice article, thanks for helping people get interested in Sequel. It's my ORM of choice, so always happy to see these articles.

Note that you could simplify your validations with the validation_helpers plugin. That way they're very similar to Active Record validations.

I agree that it can be a bit daunting that Sequel requires you to set up things in specific order. In the case of connecting to a database before defining models, it's because Sequel defines model attributes at the time of definition. In contrast, Active Record defines model attributes on runtime, I think when the first model instance is created, which I think is far from ideal.

Collapse
 
torianne02 profile image
Tori Crawford

Thank you so much for adding to the discussion! I had no idea about the validation_helpers plugin. Not having to build the validation methods is definitely a small win.

Yes, the ordering of how you build things was very confusing. I hadn't realized that I had to do this until I started hitting errors. I tried finding tutorials or any information on it outside of the official documentation but had a hard time. This is why I made sure to make a point about it in this tutorial. 😊 I really appreciate you building on it further in your comment!

Collapse
 
janko profile image
Janko Marohnić

I just remembered, if you haven't seen it already, there is a Code Order official guide that explains the ordering.

Collapse
 
edgarortegaramirez profile image
Edgar Ortega

I ❤️ Sequel!

Collapse
 
rhymes profile image
rhymes

Hi Victoria! Really nice article, I've used Sequel a bit in the past in scripts and it's a neat tool.

I love how you figured out a lot of things on your own, because I would have just used the sequel-rails gem which provides the rake/rails commands you mentioned. That's where ActiveRecord and Rails cheat a bit. AR doesn't really provide those commands, it's Rails that has them builtin.

One last thing, if you add ruby at the end of the triple ticks you can have syntax highlighting:

class Dog < Sequel::Model
  many_to_one :person

  def validate
    super
    errors.add(:name, "must be present") if name.empty?
    errors.add(:breed, "must be present") if breed.empty?
  end
end
Collapse
 
torianne02 profile image
Tori Crawford

Thank you for the tip on using Ruby! I know I can do that in markdown, but never connected being able to use it on here. 🤦‍♀️

I would have loved to use Rails on this project, but I was given specific instructions not to. I was forced to learn how to do everything "by hand" instead of having Rails do everything. It was an amazing opportunity and I learned a lot!

Collapse
 
rhymes profile image
rhymes

I would have loved to use Rails on this project, but I was given specific instructions not to. I was forced to learn how to do everything "by hand" instead of having Rails do everything. It was an amazing opportunity and I learned a lot!

Ooooh that's really great! :-)

Thanks again for the article!