Relational databases

suggest change

Ruby code talks to relational databases in three layers. Each layer builds on the one below it:

Layer What it gives you Gems
Driver A connection, raw SQL, parameter binding, result rows pg (PostgreSQL), sqlite3, mysql2 / trilogy (MySQL, MariaDB)
Toolkit Database-independent query builder, migrations, connection pool, transactions sequel
ORM Model classes with validations, associations and callbacks, on top of the toolkit features activerecord (Rails), Sequel::Model

This article gives an overview of each layer and the things they all share: placeholders, transactions, migrations and connection pooling. It uses SQLite so every example runs without a server. The same code works on PostgreSQL or MySQL once you change the connection string. Each database has its own details (type casting, upserts, streaming), and those are covered in MySQL.

The examples were run with Ruby 4.0, sqlite3 2.10 (SQLite 3.54), Sequel 5.109 and Active Record 8.1.

Installing

# Gemfile
gem "sqlite3", "~> 2.0"       # ships precompiled for common platforms
gem "pg", "~> 1.5"            # needs libpq (apt install libpq-dev / brew install libpq)
gem "sequel", "~> 5.0"
gem "activerecord", "~> 8.1"  # works fine outside Rails

You only need the driver for the databases you actually use. Sequel and Active Record load the right driver from the connection URL.

Drivers: raw SQL

A driver is the thinnest layer. You send SQL strings and get rows back. With sqlite3:

require 'sqlite3'

db = SQLite3::Database.new(':memory:')   # or a file path: 'app.db'
db.results_as_hash = true

db.execute(<<~SQL)
  CREATE TABLE books (
    id     INTEGER PRIMARY KEY,
    title  TEXT NOT NULL,
    author TEXT NOT NULL,
    year   INTEGER
  )
SQL

stmt = db.prepare('INSERT INTO books (title, author, year) VALUES (?, ?, ?)')
[
  ['Eloquent Ruby', 'Russ Olsen', 2011],
  ['Practical Object-Oriented Design', 'Sandi Metz', 2012],
  ['The Well-Grounded Rubyist', 'David A. Black', 2019]
].each { |row| stmt.execute(*row) }
stmt.close

puts db.last_insert_row_id
puts db.changes

db.execute('SELECT id, title, year FROM books WHERE year > ? ORDER BY year', [2011]) do |row|
  p row
end

p db.get_first_value('SELECT count(*) FROM books')
p db.execute('SELECT title FROM books WHERE author = :author', author: 'Sandi Metz')
3
1
{"id" => 2, "title" => "Practical Object-Oriented Design", "year" => 2012}
{"id" => 3, "title" => "The Well-Grounded Rubyist", "year" => 2019}
3
[{"title" => "Practical Object-Oriented Design"}]

The PostgreSQL driver pg works the same way, but it uses numbered $1 placeholders. By default it returns every value as a string unless you install a type map:

require 'pg'

conn = PG.connect(ENV.fetch('DATABASE_URL'))   # "postgres://app:secret@localhost/shop"
conn.type_map_for_results = PG::BasicTypeMapForResults.new(conn)

res = conn.exec_params('SELECT id, title FROM books WHERE year > $1', [2011])
res.each { |row| p row }        # {"id" => 2, "title" => "..."}

conn.transaction do |c|
  c.exec_params('UPDATE books SET year = $1 WHERE id = $2', [2012, 2])
end
conn.close

Every driver has its own placeholder syntax and result format:

Driver Placeholders Rows come back as
sqlite3 ?, :name, ?1 arrays, or hashes with results_as_hash
pg $1, $2 hashes with string keys and string values unless you set a type map
mysql2 ? (prepared statements only) hashes, with type casting
trilogy none (escape values yourself) Trilogy::Result with fields and rows

These differences are the main reason to move up a layer. Sequel and Active Record translate one query API into each database's dialect.

Never interpolate user input into SQL. "... WHERE name = '#{params[:name]}'" is an SQL injection hole. Always use placeholders, or a query builder that binds values for you. See Application security.

Connection URLs

Most deployment platforms hand you a single DATABASE_URL. Sequel and Active Record both accept one directly:

sqlite://app.db                         # Sequel: file; 'sqlite://' alone = in-memory
sqlite3:app.db                          # Active Record
postgres://app:secret@db.example.com:5432/shop?sslmode=require
mysql2://app:secret@127.0.0.1/shop      # or trilogy://...

Read it from the environment (see Environment variables) instead of putting passwords in code.

Sequel: datasets

Sequel is a small, fast toolkit with no dependencies. Its core object is the dataset. A dataset is an immutable, chainable description of a query, and it runs only when you ask for rows:

require 'sequel'

DB = Sequel.connect('sqlite://')   # e.g. 'postgres://app:secret@localhost/shop'

DB.create_table(:authors) do
  primary_key :id
  String :name, null: false, unique: true
end

DB.create_table(:books) do
  primary_key :id
  foreign_key :author_id, :authors, null: false, on_delete: :cascade
  String  :title, null: false
  Integer :year
  index :year
end

authors = DB[:authors]
books   = DB[:books]

metz  = authors.insert(name: 'Sandi Metz')     # returns the new id
olsen = authors.insert(name: 'Russ Olsen')
books.import([:author_id, :title, :year], [     # one multi-row INSERT
  [metz,  'Practical Object-Oriented Design', 2012],
  [metz,  '99 Bottles of OOP', 2016],
  [olsen, 'Eloquent Ruby', 2011]
])

recent = books.where { year >= 2012 }.order(:year)
puts recent.sql
p recent.select_map(:title)

p books.where(author_id: metz).count
p books.where(year: 2010..2015).exclude(Sequel.like(:title, '%Bottles%')).order(:year).first
p books.max(:year)
SELECT * FROM `books` WHERE (`year` >= 2012) ORDER BY `year`
["Practical Object-Oriented Design", "99 Bottles of OOP"]
2
{id: 3, author_id: 2, title: "Eloquent Ruby", year: 2011}
2016

Rows are plain hashes with symbol keys. Hash conditions (where(author_id: metz)), ranges (2010..2015 becomes year >= 2010 AND year <= 2015) and arrays (which become IN (...)) are all bound safely. The block form where { year >= 2012 } builds SQL expressions from Ruby operators.

Joins, grouping and updates:

rows = books.join(:authors, id: :author_id)
            .select(Sequel[:books][:title], Sequel[:authors][:name])
            .order(Sequel[:books][:title])
            .all
rows.each { |r| puts "#{r[:title]} - #{r[:name]}" }

p authors.left_join(:books, author_id: :id)
         .group_and_count(Sequel[:authors][:name].as(:author))
         .order(:author).all

books.where(title: 'Eloquent Ruby').update(year: 2010)
p books.where(title: 'Eloquent Ruby').get(:year)
99 Bottles of OOP - Sandi Metz
Eloquent Ruby - Russ Olsen
Practical Object-Oriented Design - Sandi Metz
[{author: "Russ Olsen", count: 1}, {author: "Sandi Metz", count: 2}]
2010

When the builder gets in the way, drop to SQL and keep the binding: DB['SELECT * FROM books WHERE year > ?', 2011].all, or DB.fetch(sql, *args).

Migrations

A migration is a versioned, ordered change to the schema. It is checked in with the code, so every developer machine, CI run and production server ends up with the same tables.

Sequel migrations

Put numbered files in a directory:

# db/migrate/001_create_authors.rb
Sequel.migration do
  change do
    create_table(:authors) do
      primary_key :id
      String :name, null: false, unique: true
    end
  end
end
# db/migrate/002_create_books.rb
Sequel.migration do
  change do
    create_table(:books) do
      primary_key :id
      foreign_key :author_id, :authors, null: false
      String  :title, null: false
      Integer :year
    end
  end
end

change works when Sequel knows how to reverse every step. For data changes, write up and down yourself:

# db/migrate/003_add_isbn_to_books.rb
Sequel.migration do
  up do
    add_column :books, :isbn, String
    self[:books].update(isbn: 'unknown')
  end

  down do
    drop_column :books, :isbn
  end
end

Run them from code, or with sequel -m db/migrate $DATABASE_URL on the command line:

Sequel.extension :migration

Sequel::Migrator.run(DB, 'db/migrate')
p DB.tables.sort
p DB[:schema_info].first
p DB.schema(:books).map(&:first)

Sequel::Migrator.run(DB, 'db/migrate', target: 1)   # roll back to version 1
p DB.tables.sort
Sequel::Migrator.run(DB, 'db/migrate')
p Sequel::Migrator.is_current?(DB, 'db/migrate')
[:authors, :books, :schema_info]
{version: 3}
[:id, :author_id, :title, :year, :isbn]
[:authors, :schema_info]
true

On databases with transactional DDL (PostgreSQL, SQLite), Sequel runs each migration in a transaction, so a migration that fails halfway leaves nothing behind. MySQL commits implicitly after most DDL statements, so a failed migration there may need manual cleanup.

Active Record migrations

Active Record migrations are classes tagged with the framework version they were written for:

require 'active_record'

ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: 'library.sqlite3', pool: 5)
# or: ActiveRecord::Base.establish_connection(ENV.fetch('DATABASE_URL'))

class CreateLibrary < ActiveRecord::Migration[8.1]
  def change
    create_table :authors do |t|
      t.string :name, null: false, index: { unique: true }
      t.timestamps
    end

    create_table :books do |t|
      t.references :author, null: false, foreign_key: true
      t.string  :title, null: false
      t.integer :year
      t.timestamps
    end
  end
end

ActiveRecord::Migration.verbose = false
CreateLibrary.migrate(:up)
p ActiveRecord::Base.connection.tables.sort
["authors", "books"]

In a Rails app you don't call migrate yourself. Files in db/migrate/ named 20261017120000_create_library.rb are applied by bin/rails db:migrate, and the versions that ran are recorded in a schema_migrations table.

Some rules apply to migrations in either library:

ORMs: models

Sequel::Model

class Author < Sequel::Model
  one_to_many :books
end

class Book < Sequel::Model
  many_to_one :author
  plugin :validation_helpers

  def validate
    super
    validates_presence [:title, :author_id]
    validates_integer :year, allow_nil: true
  end
end

metz = Author.create(name: 'Sandi Metz')
metz.add_book(title: 'Practical Object-Oriented Design', year: 2012)
metz.add_book(title: '99 Bottles of OOP', year: 2016)
Author.create(name: 'Russ Olsen').add_book(title: 'Eloquent Ruby', year: 2011)

book = Book.first(title: 'Eloquent Ruby')
puts book.author.name
p metz.books.map(&:title)

bad = Book.new(title: '', year: 'soon')
p bad.valid?
p bad.errors
Russ Olsen
["Practical Object-Oriented Design", "99 Bottles of OOP"]
false
{title: ["is not present"], author_id: ["is not present"], year: ["is not a number"]}

Sequel models read their columns from the table when the class is defined, so the table has to exist first. Run migrations before you load the models.

Active Record

class Author < ActiveRecord::Base
  has_many :books, dependent: :destroy
  validates :name, presence: true, uniqueness: true
end

class Book < ActiveRecord::Base
  belongs_to :author
  validates :title, presence: true
  scope :since, ->(y) { where(year: y..) }
end

metz = Author.create!(name: 'Sandi Metz')
metz.books.create!(title: 'Practical Object-Oriented Design', year: 2012)
metz.books.create!(title: '99 Bottles of OOP', year: 2016)
Author.create!(name: 'Russ Olsen').books.create!(title: 'Eloquent Ruby', year: 2011)

p Book.since(2012).order(:year).pluck(:title)
puts Book.since(2012).joins(:author).where(authors: { name: 'Sandi Metz' }).to_sql
p Book.group(:author_id).count

dup = Author.new(name: 'Sandi Metz')
p dup.save
p dup.errors.full_messages
["Practical Object-Oriented Design", "99 Bottles of OOP"]
SELECT "books".* FROM "books" INNER JOIN "authors" ON "authors"."id" = "books"."author_id" WHERE "books"."year" >= 2012 AND "authors"."name" = 'Sandi Metz'
{1 => 2, 2 => 1}
false
["Name has already been taken"]

save returns false when validation fails. save! and create! raise ActiveRecord::RecordInvalid instead. Use the bang versions in scripts and inside transactions so failures can't go unnoticed. A uniqueness validation can still lose a race between two processes, so always back it with a unique index, as the migration above does.

The N+1 query problem

Lazy associations make it easy to run one query per row. Turn on logging to see it:

require 'logger'
ActiveRecord::Base.logger = Logger.new($stdout, formatter: ->(*, msg) { "#{msg}\n" })
ActiveRecord::LogSubscriber.colorize_logging = false

puts '-- N+1'
Author.order(:id).each { |a| a.books.size }
puts '-- includes'
Author.includes(:books).order(:id).each { |a| a.books.size }
-- N+1
  Author Load (2.2ms)  SELECT "authors".* FROM "authors" ORDER BY "authors"."id" ASC
  Book Count (3.5ms)  SELECT COUNT(*) FROM "books" WHERE "books"."author_id" = ?  [["author_id", 1]]
  Book Count (0.8ms)  SELECT COUNT(*) FROM "books" WHERE "books"."author_id" = ?  [["author_id", 2]]
-- includes
  Author Load (0.3ms)  SELECT "authors".* FROM "authors" ORDER BY "authors"."id" ASC
  Book Load (0.4ms)  SELECT "books".* FROM "books" WHERE "books"."author_id" IN (?, ?)  [["author_id", 1], ["author_id", 2]]

With 1,000 authors the first version runs 1,001 queries. Sequel's equivalent of includes is eager:

DB.loggers << Logger.new($stdout, formatter: ->(*, msg) { "#{msg}\n" })
Author.eager(:books).all.each { |a| puts "#{a.name}: #{a.books.size}" }
(0.000046s) SELECT * FROM `authors`
(0.000036s) SELECT * FROM `books` WHERE (`books`.`author_id` IN (1, 2))
Sandi Metz: 2
Russ Olsen: 1

Active Record can also raise an error when you lazy-load. Call Author.strict_loading.each { ... }, or set self.strict_loading_by_default = true on a model. Sequel offers the same through plugin :forbid_lazy_load.

Transactions

A transaction groups statements so that either all of them take effect or none do. Both libraries use a block: the transaction commits if the block returns normally and rolls back if it raises.

Sequel

DB = Sequel.connect('sqlite://bank.db')
DB.create_table!(:accounts) do
  primary_key :id
  String  :owner, null: false
  Integer :balance, null: false
  constraint(:non_negative) { balance >= 0 }
end
accounts = DB[:accounts]
accounts.import([:owner, :balance], [['alice', 100], ['bob', 50]])

def transfer(from, to, amount)
  DB.transaction do
    DB[:accounts].where(owner: from).update(balance: Sequel[:balance] - amount)
    DB[:accounts].where(owner: to).update(balance: Sequel[:balance] + amount)
  end
end

transfer('alice', 'bob', 30)
p accounts.order(:id).select_map([:owner, :balance])

begin
  transfer('alice', 'bob', 500)
rescue Sequel::CheckConstraintViolation => e
  puts "rolled back: #{e.class}"
end
p accounts.order(:id).select_map([:owner, :balance])
[["alice", 70], ["bob", 80]]
rolled back: Sequel::CheckConstraintViolation
[["alice", 70], ["bob", 80]]

balance - amount is computed by the database (SET balance = balance - 30). Reading the balance into Ruby, subtracting, and writing it back would lose updates when two requests run at the same time.

Rolling back without an error, savepoints, and after-commit hooks:

DB.transaction do
  accounts.where(owner: 'bob').update(balance: 0)
  raise Sequel::Rollback          # rolls back, and isn't re-raised
end
p accounts.where(owner: 'bob').get(:balance)

DB.transaction do
  accounts.insert(owner: 'carol', balance: 10)
  DB.transaction(savepoint: true) do
    accounts.insert(owner: 'dave', balance: 10)
    raise Sequel::Rollback        # undoes only dave
  end
  DB.after_commit { puts 'committed, send emails now' }
end
p accounts.select_order_map(:owner)
80
committed, send emails now
["alice", "bob", "carol"]

A nested DB.transaction without savepoint: true just joins the outer transaction. Put side effects such as emails, job enqueues and HTTP calls in after_commit. Otherwise they can fire for a transaction that later rolls back.

Active Record

ActiveRecord::Base.transaction do
  olsen = Author.find_by!(name: 'Russ Olsen')
  olsen.books.create!(title: 'Getting Clojure', year: 2018)
  raise ActiveRecord::Rollback      # silent rollback
end
p Book.count

ActiveRecord::Base.transaction do
  Author.create!(name: 'Avdi Grimm')
  ActiveRecord::Base.transaction(requires_new: true) do   # savepoint
    Author.create!(name: 'Nobody')
    raise ActiveRecord::Rollback
  end
end
p Author.order(:id).pluck(:name)

begin
  Book.transaction do
    Book.create!(title: 'Draft', author: metz)
    Book.create!(title: '', author: metz)
  end
rescue ActiveRecord::RecordInvalid => e
  puts e.message
end
p Book.where(title: 'Draft').exists?
3
["Sandi Metz", "Russ Olsen", "Avdi Grimm"]
Validation failed: Title can't be blank
false

A common trap: inside a nested transaction block without requires_new: true, raise ActiveRecord::Rollback is swallowed by the inner block and rolls back nothing. Use requires_new: true whenever you mean "this part may fail on its own". Model callbacks after_commit and after_rollback give you the same hooks as Sequel's.

Isolation levels and retries

Under concurrency, a stricter isolation level can make the database abort a transaction with a serialization failure or a deadlock error. The fix is to retry the whole transaction:

# Sequel (PostgreSQL)
DB.transaction(isolation: :serializable,
               retry_on: [Sequel::SerializationFailure], num_retries: 3) do
  # ...
end

# Active Record
attempts = 0
begin
  ActiveRecord::Base.transaction(isolation: :serializable) do
    # ...
  end
rescue ActiveRecord::SerializationFailure, ActiveRecord::Deadlocked
  retry if (attempts += 1) < 3
  raise
end

Only retry code that is safe to run again. Everything inside the block runs again, so keep external side effects out of it.

For "read a row, then change it" logic, lock the row instead: Account.lock.find(id) in Active Record, or DB[:accounts].where(id: id).for_update.first in Sequel. Both issue SELECT ... FOR UPDATE. SQLite locks the whole database and ignores FOR UPDATE.

Connection pooling

A database connection is a stateful socket, and only one thread can use it at a time. Both libraries keep a pool. A thread checks out a connection, uses it and returns it. If every connection is busy, the thread waits up to a timeout and then raises.

DB = Sequel.connect('sqlite://bank.db', max_connections: 5, pool_timeout: 2)

p DB.pool.max_size
threads = 10.times.map do
  Thread.new { DB.synchronize { |conn| sleep 0.05; conn.class } }
end
p threads.map(&:value).uniq
p DB.pool.size
5
[SQLite3::Database]
5

Ten threads shared five connections. The other five waited their turn, and none of them waited longer than pool_timeout, so Sequel::PoolTimeout was never raised. You rarely call synchronize yourself, because every query checks a connection out and returns it automatically. Explicit checkout is useful when several statements must use the same session, for example after a SET command.

In Active Record, pool: (default 5) sets the size and checkout_timeout: sets the wait. In threads you start yourself, wrap the work in with_connection so the connection goes back to the pool promptly:

p ActiveRecord::Base.connection_pool.size
t = 3.times.map { Thread.new { ActiveRecord::Base.with_connection { Book.count } } }
p t.map(&:value)
5
[3, 3, 3]

To size a pool:

See Thread for more on Ruby concurrency.

Testing against a database

The usual approach is to run each test inside a transaction and roll it back afterwards. That's fast and leaves no data behind:

# Sequel + Minitest
module TransactionalTests
  def run(*args, &block)
    DB.transaction(rollback: :always, auto_savepoint: true) { super }
  end
end
Minitest::Test.prepend(TransactionalTests)

Rails does the same automatically (use_transactional_tests). Test against the same database engine you use in production. SQLite is forgiving in ways PostgreSQL and MySQL are not: it doesn't enforce declared column types or string lengths. A real server in CI is described in Testing in CI.

Which one to use

For MySQL-specific setup, mysql2 vs trilogy, upserts and streaming large results, see MySQL. For a document database, see MongoDB. To store user passwords in a table, see Password hashing.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents