skip to content

In a Rails app using the strong_migrations gem, what happens when a migration runs a risky operation, and what is safety_assured for?

level: juniorimportance: should knowfreq 38%

answer

  1. checker sits in front of every migration call
  2. raises before any SQL runs
  3. StrongMigrations::UnsafeMigration plus a safer recipe
  4. safety_assured = you vouch, nothing changes
  5. start_after and rollbacks are not checked

basics

~20 s

strong_migrations checks each schema call a Rails migration makes and stops risky ones, such as blocking index builds or column drops, with StrongMigrations::UnsafeMigration and a safer recipe. safety_assured { ... } skips the check for a step you made safe.

solid answer

~40 s

The gem prepends a module to `ActiveRecord::Migration`, so every schema method a migration calls (`add_index`, `remove_column`, `change_column_null`, `execute` and so on) passes through its checker first. When a call matches a check, it raises `StrongMigrations::UnsafeMigration` before the SQL runs, under a `=== Dangerous operation detected #strong_migrations ===` header that shows the safe version: build the index with `algorithm: :concurrently`, ignore a column before dropping it, add a constraint with `validate: false`. `safety_assured { ... }` tells the checker to let the wrapped calls through. It changes no SQL; it records that you did the safe steps, such as deploying `ignored_columns` first. `remove_column`, `rename_column` and `execute` stop every time unless wrapped, because the gem cannot see what you did outside the migration. Migrations older than `StrongMigrations.start_after`, and rollbacks, are not checked by default.

code

ruby · 7 lines
ruby
# Second release: the ignore line is already deployed on Event
class RemoveLegacyPayloadFromEvents < ActiveRecord::Migration[8.1]
  def change
    # remove_column stops unless wrapped in this block
    safety_assured { remove_column :events, :legacy_payload, :jsonb }
  end
end

go deeper

for a junior

Know what the gem does when it objects: it stops the migration with StrongMigrations::UnsafeMigration and prints a safer version to copy. Read the message before reaching for safety_assured.

for a middle

Explain the mechanism: the checker sees every schema call, raises before SQL runs, and skips calls in safety_assured, rollbacks and versions up to start_after.

for a senior

Treat each safety_assured block as a claim to verify in review, keep development on the production database engine, and add custom checks for your own hot tables.

for a principal

Decide where the gem sits in the release process: what counts as an acceptable safety_assured, who reviews it, and when safe_by_default is worth its implicit behaviour.

## What the gem is for **strong_migrations** is a gem that catches **unsafe migrations** before they reach a busy production database. An operation counts as dangerous when it either blocks reads or writes for more than a few seconds once its lock is granted, or has a good chance of raising errors in the application servers that are still running. Typical examples are building an index the blocking way, dropping a column the running code still uses, and adding a constraint that checks every existing row while holding a lock. You add `gem "strong_migrations"` to the Gemfile and run `bin/rails generate strong_migrations:install`, which writes `config/initializers/strong_migrations.rb`. ## How a check fires The gem prepends a module to `ActiveRecord::Migration`. Schema methods inside a migration (`add_index`, `add_column`, `remove_column`, `add_foreign_key`, `change_column_null`, `execute` and the rest) reach the migration through `method_missing`, and the gem's version of `method_missing` hands each call to a **checker** first: 1. The checker sets the configured timeouts on the connection (see below). 2. It decides whether the call is exempt: wrapped in `safety_assured`, part of a rollback, or in a migration whose version is at or below `start_after`. 3. If not, it runs the check for that method and any custom checks you registered. 4. A failed check raises **`StrongMigrations::UnsafeMigration`** with a message headed `=== Dangerous operation detected #strong_migrations ===`. The message is written for your exact call: it prints the safer migration, often split into two files, with your table and column names filled in. 5. If every check passes, the original method runs and issues its SQL. Because the error is raised before that statement is sent, the risky change never reaches the table, and in a normal transactional migration any earlier statements roll back with it. The checks run wherever the migration runs, so you normally meet them in development, long before a deploy. ## What safety_assured means, and what it does not `safety_assured { ... }` sets a flag that makes the checker skip the calls inside the block. It is a **statement by the author**, not a fix: - It does **not** rewrite the SQL. `safety_assured { add_index :events, :account_id }` still builds the index the blocking way. - It is the expected last step of several recipes. To drop a column you first deploy `self.ignored_columns += ["legacy_payload"]` on the model, then wrap `remove_column` in `safety_assured`, because the gem cannot see that the ignore line has already shipped. - `remove_column`, `rename_column`, `rename_table` and `execute` raise **every time** without it, outside the exemptions above: the gem cannot know which code reads the column, or what raw SQL does. - Reviewers should read every `safety_assured` block as a claim to check, the same way they read a `# rubocop:disable` comment. ## What is checked where | Check family | Runs on | Example | |---|---|---| | General | every supported engine; the drop, rename and `execute` checks on any adapter | `remove_column`, `rename_column`, `change_column`, `execute`, `add_foreign_key`, `add_check_constraint` | | Postgres-specific | PostgreSQL | `add_index` or `add_reference` without a concurrent index, `change_column_null` to false, a volatile column default | | MySQL/MariaDB-specific | MySQL, MariaDB | `algorithm: :copy`, `lock:` options | | Opt-in | where enabled | `remove_index` without `algorithm: :concurrently` | The gem supports PostgreSQL, MySQL and MariaDB. On another adapter, such as the SQLite database a new Rails app starts with, it prints an unsupported-adapter warning and the Postgres checks do not apply, so teams that develop on SQLite but deploy to PostgreSQL miss most of the protection until development matches production. ## Settings you meet first - **`StrongMigrations.start_after`**: migrations with a version at or below it are treated as safe. The install generator fills in the current timestamp so the gem does not complain about history. - **`StrongMigrations.check_down`**: checks are skipped on rollback unless you set this to `true`. - **`StrongMigrations.disable_check(:add_index)`** and **`StrongMigrations.enable_check(:remove_index)`** switch individual checks. - **`StrongMigrations.safe_by_default = true`** makes a few PostgreSQL operations (adding or removing an index, adding a foreign key or check constraint, setting NOT NULL) run as their safe version instead of raising. - **`StrongMigrations.add_check { |method, args| stop! "..." }`** adds a team rule, such as no new indexes on a hot table. - The **`SAFETY_ASSURED`** environment variable switches every check off for the run. It exists for emergencies; using it to push a blocked deploy through defeats the gem. The gem is a reviewer that never gets tired, not a guarantee: it does not detect a dangerous backfill, and a `safety_assured` block is only as honest as its author.

  • Your team develops on SQLite and deploys to PostgreSQL. What does strong_migrations catch?
    Less than you think. On SQLite the gem warns that the adapter is unsupported, and the Postgres checks (non-concurrent `add_index`, unvalidated foreign keys, `change_column_null`) never fire. The general checks such as `remove_column` and `execute` still stop. Run development and CI on PostgreSQL, and set `StrongMigrations.target_version` to production's major version so the checks match it.
  • How would you add a team rule, such as no new indexes on the events table without review?
    Register a custom check in the initializer: `StrongMigrations.add_check do |method, args| stop! "Ask the data team first" if method == :add_index && args[0].to_s == "events" end`. `stop!` raises `StrongMigrations::UnsafeMigration` like a built-in check, and `safety_assured` skips custom checks too.

  • safety_assured makes the wrapped operation safe on a big table
  • strong_migrations only prints warnings; the migration still runs
  • the gem can see that ignored_columns is already deployed
  • setting SAFETY_ASSURED=1 is a fine way to unblock a deploy
  • strong_migrations checks every migration ever written, so installing it breaks history