Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
O

online_migrations

> 后端框架
Open source

Catch unsafe PostgreSQL migrations in development and run them easier in production (code helpers for table/column renaming, changing column type, adding column

754 stars0 likes1 views
WebsiteGitHub

About

Catch unsafe PostgreSQL migrations in development and run them easier in production (code helpers for table/column renaming, changing column type, adding column

OnlineMigrations

Catch unsafe PostgreSQL migrations in development and run them easier in production.

:white_check_mark: Detects potentially dangerous operations
:white_check_mark: Prevents them from running by default
:white_check_mark: Provides instructions and helpers on safer ways to do what you want

Note: You probably don't need this gem for smaller projects, as operations that are unsafe at scale can be perfectly safe on smaller, low-traffic tables.

Cool, but there is a strong_migrations already

See comparison to strong_migrations

Requirements

  • Ruby 3.3+
  • Rails 7.2+
  • PostgreSQL 12+

For older Ruby and Rails versions you can use older versions of this gem.

Note: Since some migration helpers use database VIEWs to implement their logic, it is recommended to use structure.sql schema format, or otherwise add some gem (like scenic) to be able to dump them into the schema.rb.

Installation

Add this line to your application's Gemfile:

ruby
gem 'online_migrations'

And then run:

bash
$ bundle install
$ bin/rails generate online_migrations:install
$ bin/rails db:migrate

Note: If you do not have plans on using background data migrations or background schema migrations features, then you can delete the generated migration and regenerate it later, if needed.

Upgrading

If you're already using background data migrations or background schema migrations, your background migrations tables may require additional columns. After every upgrade run:

bash
$ bin/rails generate online_migrations:upgrade
$ bin/rails db:migrate

Motivation

Writing a safe migration can be daunting. Numerous articles have been written on the topic and a few gems are trying to address the problem. Even for someone who has a pretty good command of PostgreSQL, remembering all the subtleties of explicit locking can be problematic.

Online Migrations was created to catch dangerous operations and provide a guidance and code helpers to run them safely.

An operation is classified as dangerous if it either:

  • Blocks reads or writes for more than a few seconds (after a lock is acquired)
  • Has a good chance of causing application errors

Example

When you run a migration that's potentially dangerous, you'll see an error message like:

txt
⚠️  [online_migrations] Dangerous operation detected ⚠️

Active Record caches database columns at runtime, so if you drop a column, it can cause exceptions until your app reboots.
A safer approach is to:

1. Ignore the column:

  class User  {
       "name" => "first_name"
     }
   }

Note: You also need to temporarily enable partial writes (is disabled by default in Active Record >= 7) until the process of column rename is fully done.

ruby
# config/application.rb
# For Active Record >= 7
config.active_record.partial_inserts = true

# Or for Active Record = 7),
then you need to ignore the old column:

```ruby
class User  "users"
}
  1. Deploy

  2. Create a VIEW:

    ruby
    class InitializeRenameClientsToUsers = 1", name: "name_check"
      end
    end

:white_check_mark: **Good**

Add the check constraint without validating existing rows, and then validate them in a separate transaction:

```ruby
class AddCheckConstraint = 1", name: "name_check", validate: false
    validate_check_constraint :users, name: "name_check"
  end
end

Note: If you forget disable_ddl_transaction!, the migration will fail.

Setting NOT NULL on an existing column

:x: Bad

Setting NOT NULL on an existing column blocks reads and writes while every row is checked.

ruby
class ChangeUsersNameNull = 5.1
      # ...
    end
  end
end

Hash indexes

:x: Bad - PostgreSQL < 10

Hash index operations are not WAL-logged, so hash indexes might need to be rebuilt with REINDEX after a database crash if there were unwritten changes. Also, changes to hash indexes are not replicated over streaming or file-based replication after the initial base backup, so they give wrong answers to queries that subsequently use them. For these reasons, hash index use is discouraged.

ruby
class AddIndexToUsersOnEmail < ActiveRecord::Migration[8.0]
  def change
    add_index :users, :email, unique: true, using: :hash
  end
end

:white_check_mark: Good - PostgreSQL < 10

Use B-tree indexes instead.

ruby
class AddIndexToUsersOnEmail < ActiveRecord::Migration[8.0]
  def change
    add_index :users, :email, unique: true # B-tree by default
  end
end

Adding multiple foreign keys

:x: Bad

Adding multiple foreign keys in a single migration blocks writes on all involved tables until migration is completed. Avoid adding foreign key more than once per migration file, unless the source and target tables are identical.

ruby
class CreateUserProjects < ActiveRecord::Migration[8.0]
  def change
    create_table :user_projects do |t|
      t.belongs_to :user, foreign_key: true
      t.belongs_to :project, foreign_key: true
    end
  end
end

:white_check_mark: Good

Add additional foreign keys in separate migration files. See adding a foreign key for how to properly add foreign keys.

ruby
class CreateUserProjects < ActiveRecord::Migration[8.0]
  def change
    create_table :user_projects do |t|
      t.belongs_to :user, foreign_key: true
      t.belongs_to :project, foreign_key: false
    end
  end
end

class AddForeignKeyFromUserProjectsToProject < ActiveRecord::Migration[8.0]
  def change
    add_foreign_key :user_projects, :projects
  end
end

Removing a table with multiple foreign keys

:x: Bad

Removing a table with multiple foreign keys blocks reads and writes on all involved tables until migration is completed. Remove all the foreign keys first.

Assuming, projects has foreign keys on users.id and repositories.id:

ruby
class DropProjects < ActiveRecord::Migration[8.0]
  def change
    drop_table :projects
  end
end

:white_check_mark: Good

Remove all the foreign keys first:

ruby
class RemoveProjectsUserFk < ActiveRecord::Migration[8.0]
  def change
    remove_foreign_key :projects, :users
  end
end

class RemoveProjectsRepositoryFk < ActiveRecord::Migration[8.0]
  def change
    remove_foreign_key :projects, :repositories
  end
end

Then remove the table:

ruby
class DropProjects < ActiveRecord::Migration[8.0]
  def change
    drop_table :projects
  end
end

Mismatched reference column types

:x: Bad

Reference columns should be of the same type as the referenced primary key. Otherwise, there's a risk of bugs caused by IDs representable by one type but not the other.

Assuming, there is a users table with bigint primary key type:

ruby
class AddUserIdToProjects < ActiveRecord::Migration[8.0]
  def change
    add_column :projects, :user_id, :integer
  end
end

:white_check_mark: Good

Add a reference column of the same type as a referenced primary key.

Assuming, there is a users table with bigint primary key type:

ruby
class AddUserIdToProjects < ActiveRecord::Migration[8.0]
  def change
    add_column :projects, :user_id, :bigint
  end
end

Adding a single table inheritance column

:x: Bad

Adding a single table inheritance column might cause errors in old instances of your application.

ruby
class AddTypeToUsers < ActiveRecord::Migration[8.0]
  def change
    add_column :users, :string, :type, default: "Member"
  end
end

After the migration was ran and the column was added, but before the code is fully deployed to all instances, an old instance may be restarted (due to an error etc). And when it will fetch 'User' records from the database, 'User' will look for a 'Member' subclass (from the 'type' column) and fail to locate it unless it is already defined.

:white_check_mark: Good

A safer approach is to:

  1. ignore the column:

    ruby
    class User < ApplicationRecord
      self.ignored_columns += ["type"]
    end
  2. deploy

  3. remove the column ignoring from step 1 and apply initial code changes

  4. deploy

Changing the default value of a column

:x: Bad

Active Record < 7 enables partial writes by default, which can cause incorrect values to be inserted when changing the default value of a column.

ruby
class ChangeSomeColumnDefault < ActiveRecord::Migration[8.0]
  def change
    change_column_default :users, :some_column, from: "old", to: "new"
  end
end

User.create!(some_column: "old") # can insert "new"

:white_check_mark: Good

Disable partial writes in config/application.rb. For Active Record < 7, use:

ruby
config.active_record.partial_writes = false

For Active Record 7, use:

ruby
config.active_record.partial_inserts = false

Assuring Safety

To mark a step in the migration as safe, despite using a method that might otherwise be dangerous, wrap it in a safety_assured block.

ruby
class MySafeMigration < ActiveRecord::Migration[8.0]
  def change
    safety_assured { remove_column :users, :some_column }
  end
end

Certain methods like execute and change_table cannot be inspected and are prevented from running by default. Make sure what you're doing is really safe and use this pattern.

Configuring the gem

Read configuring.md.

Background Data Migrations

Read background_data_migrations.md on how to perform data migrations on large tables.

Background Schema Migrations

Read background_schema_migrations.md on how to perform background schema migrations on large tables.

Credits

Thanks to strong_migrations gem, GitLab and maintenance_tasks gem for the original ideas.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/fatkodima/online_migrations.

Development

After checking out the repo, run bundle install to install dependencies. Run createdb online_migrations_test to create a test database. Then, run bundle exec rake test to run the tests. This project uses multiple Gemfiles to test against multiple versions of Active Record; you can run the tests against the specific version with BUNDLE_GEMFILE=gemfiles/activerecord_61.gemfile bundle exec rake test.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Additional resources

Alternatives:

  • https://github.com/ankane/strong_migrations
  • https://github.com/LendingHome/zero_downtime_migrations
  • https://github.com/braintree/pg_ha_migrations
  • https://github.com/doctolib/safe-pg-migrations

Interesting reads:

  • Explicit Locking
  • When Postgres blocks: 7 tips for dealing with locks
  • PostgreSQL rocks, except when it blocks: Understanding locks
  • PostgreSQL at Scale: Database Schema Changes Without Downtime
  • [Adding a NOT NULL CONSTRAINT on PG Faster with Minimal Locking](https://medium.com/doctolib-engineering/adding-a-not-null-constraint-on-pg-faster-with-minimal-locking-

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubyactiverecordgemmigrationspostgresql

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架