What is Sequel?
Sequel is a gem that allows you to access your database, no Rails required.
You can connect to your database in different ways.
Mostly two:
- By sending raw SQL commands
- By using an ORM
Here’s an example, using raw SQL & the MySQL database.
require 'mysql2' client = Mysql2::Client.new(host: "localhost") results = client.query("SELECT * FROM users WHERE age > 21")
The results?
An array of hashes with the data.
Now:
If we want to work with the data in an Object-Oriented way, we will need to make the results into objects.
That’s a big part of what an ORM does.
What’s an ORM?
ORM stands for “Object-Relational-Mapping”.
Sequel, named after the vocalization of SQL (a query language for databases), is an ORM.
Let’s discover how to use it!
Sequel Example: Connecting to A Database
The first step to start using Sequel is to connect to a database.
Here’s an example:
require 'sequel' DB = Sequel.sqlite('/tmp/testing.db')
This creates a Sequel::Database
object & assigns it to DB
.
We’re using the SQLite3 database here.
But you can use others:
Sequel.postgres
Sequel.mysql2
Sequel.oracle
What’s next?
You need to create a table to store data.
Here’s how to create it:
unless DB.table_exists?(:fruits) DB.create_table :fruits do primary_key :id column :name, String column :amount, Integer end end
There’s a migration system you can use.
But it’s optional.
Now we are ready to start adding data & querying the database!
How to Use Sequel Datasets
You need a dataset object to interact with a specific table on the database.
Here’s how to get one:
table = DB[:fruits] # Sequel::SQLite::Dataset
Great!
Now we can add a few records with the insert
method.
Like this:
table.insert(name: "Orange", amount: 10) table.insert(name: "Apple", amount: 2) table.insert(name: "Banana", amount: 7)
Let’s get a count:
table.count # 3
Let’s get all the entries in the dataset:
table.all # [ # { id: 1, name: "Orange", amount: 10 }, # { id: 2, name: "Apple", amount: 2 }, # { id: 3, name: "Banana", amount: 7 } # ]
Hey!
This looks like an array of hashes.
Well, you’re right.
That’s exactly what this is.
Sequel
allows you to query the database without a model.
But we can use models.
Here’s how…
How to Use Models in Sequel
A Sequel
model looks a lot like an ActiveRecord
model.
Here’s an example:
class Fruit < Sequel::Model end
Models behave exactly like a dataset, but they wrap the results in the model class.
Take a look:
Fruit.first # Fruit @values={:id=>1, :name=>"Orange", :amount=>10}
We can use the same Sequel::Dataset
methods.
So there is no “magic” here.
A few more examples:
Fruit.map(:name) # ["Orange", "Apple", "Banana"] Fruit.where(name: "Apple").or(amount: 10).map(:name) # ["Orange", "Apple"] Fruit.first[:amount] # 10
Very nice!
Sequel vs ActiveRecord
Now that you’ve learned how awesome Sequel
is, you may be wondering how it compares to ActiveRecord
.
Well, ActiveRecord
is the default ORM for Rails.
And Rails really likes conventions.
So I don’t think it’s worth trying to replace ActiveRecord
with Sequel
in a Rails app.
However.
If you’re using another framework, like Sinatra, then Sequel
is a great choice!
Summary
You have learned about working with databases in Ruby using an ORM, in this case, the Sequel Ruby gem.
Now it’s your turn to give this a try & have fun!
Thanks for reading.
This is a great post on how SQL can be used in a Ruby app and how it compares to Rails ActiveRecord. I am also reading your book ‘Ruby Deep Dive’ and really like how you keep the topics clean and concise. Thanks for what you provide to the community! You are a true asset!
Hi Rick,
thanks a lot for you comment! 🙂
It was the first time I heard about Sequel and I found it very interesting. Thanks for sharing.
Nice! I’m glad you learned something new 🙂
Nice article, I know about Sequel and I think it is superior to ActiveRecord in many aspects. First, performance, sequel is faster than ActiveRecord. Second, is connections management, while ActiveRecord creates and assigns a connection to each thread and it doesn’t release it until the thread is dead, Sequel just reserves the connection when a query is about to be sent to the db server, once the query is over the connection is returned to the pool. This seems simple, but it’s a killer feature especially in multithreaded environments like Sidekiq.
Third, its Api, Active record creates a model instance for every record in the query result, those records are huge and in some cases you may not need them. For example in an Api that returns Json, with sequel you don’t even need a model class, you just serialize the hashes, no waste here, but with AR it creates a new object for every hash of the results, then you convert them back to Json, a lot of waste in time and memory. There are other things, but these are just a subset of the cool things that makes Sequel great and make me love it.
Here a great video of the creator of Sequel about its internals, it’s definitely worth watching.
https://youtu.be/RuGZCcEL2F8