Catch unsafe PostgreSQL migrations in development and run them easier in production (code helpers for table/column renaming, changing column type, adding column
Catch unsafe PostgreSQL migrations in development and run them easier in production (code helpers for table/column renaming, changing column type, adding column
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.
strong_migrations alreadySee comparison to strong_migrations
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.
Add this line to your application's Gemfile:
gem 'online_migrations'And then run:
$ bundle install
$ bin/rails generate online_migrations:install
$ bin/rails db:migrateNote: 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.
If you're already using background data migrations or background schema migrations, your background migrations tables may require additional columns. After every upgrade run:
$ bin/rails generate online_migrations:upgrade
$ bin/rails db:migrateWriting 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:
When you run a migration that's potentially dangerous, you'll see an error message like:
⚠️ [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.
# 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"
}Deploy
Create a VIEW:
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
endNote: If you forget disable_ddl_transaction!, the migration will fail.
:x: Bad
Setting NOT NULL on an existing column blocks reads and writes while every row is checked.
class ChangeUsersNameNull = 5.1
# ...
end
end
end: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.
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.
class AddIndexToUsersOnEmail < ActiveRecord::Migration[8.0]
def change
add_index :users, :email, unique: true # B-tree by default
end
end: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.
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.
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: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:
class DropProjects < ActiveRecord::Migration[8.0]
def change
drop_table :projects
end
end:white_check_mark: Good
Remove all the foreign keys first:
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
endThen remove the table:
class DropProjects < ActiveRecord::Migration[8.0]
def change
drop_table :projects
end
end: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:
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:
class AddUserIdToProjects < ActiveRecord::Migration[8.0]
def change
add_column :projects, :user_id, :bigint
end
end:x: Bad
Adding a single table inheritance column might cause errors in old instances of your application.
class AddTypeToUsers < ActiveRecord::Migration[8.0]
def change
add_column :users, :string, :type, default: "Member"
end
endAfter 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:
ignore the column:
class User < ApplicationRecord
self.ignored_columns += ["type"]
enddeploy
remove the column ignoring from step 1 and apply initial code changes
deploy
: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.
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:
config.active_record.partial_writes = falseFor Active Record 7, use:
config.active_record.partial_inserts = falseTo mark a step in the migration as safe, despite using a method that might otherwise be dangerous, wrap it in a safety_assured block.
class MySafeMigration < ActiveRecord::Migration[8.0]
def change
safety_assured { remove_column :users, :some_column }
end
endCertain 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.
Read configuring.md.
Read background_data_migrations.md on how to perform data migrations on large tables.
Read background_schema_migrations.md on how to perform background schema migrations on large tables.
Thanks to strong_migrations gem, GitLab and maintenance_tasks gem for the original ideas.
Bug reports and pull requests are welcome on GitHub at https://github.com/fatkodima/online_migrations.
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.
Alternatives:
Interesting reads:
No open issues yet, or sync has not completed.