A Rails 8.1 migration fails halfway on MySQL after working on PostgreSQL; why is the schema left half-changed, and how do you recover and prevent it?
answer
- supports_ddl_transactions? is false
- no transaction around the migration
- version row written only on success
- rerun fails on the first step
- one DDL step per migration
basics
~20 sMySQL commits each DDL statement immediately, so Rails does not wrap MySQL migrations in a transaction. Steps before the failure stay applied while the version is never recorded; recover by finishing or undoing those steps by hand, and prevent it with one schema change per migration.
solid answer
~40 sRails wraps a migration in a transaction only when the adapter's `supports_ddl_transactions?` is true. PostgreSQL's is; the MySQL adapters inherit `false`, because MySQL commits implicitly around DDL. So a migration that adds `reservations.channel`, adds an index, then fails on a foreign key leaves the column and index in place, while the `schema_migrations` row, written only after `migrate` succeeds, is missing. `db:migrate` then retries from the top and fails on the first step with a duplicate-column error. Recovery: inspect the table, then either undo the applied steps by hand or make the migration skip them (`if_not_exists: true`, `if_exists: true`) and rerun. Prevention: one DDL change per migration, data changes in separate migrations, and a rehearsal on a production-sized copy.
go deeper
Recall that a failed migration on MySQL can leave some changes applied because MySQL does not undo DDL.
Explain supports_ddl_transactions?, why the version row is missing, and why a rerun fails on its first step.
Recover a stuck migration from the real schema, use if_not_exists: or if_exists: deliberately, and split risky migrations.
Set migration rules for a team moving engines, including rehearsal on production-sized copies and safety tooling.
## Why PostgreSQL hid the problem On PostgreSQL, schema changes are transactional: `CREATE TABLE`, `ALTER TABLE` and `CREATE INDEX` can sit inside a transaction and roll back with it. Rails uses that. Its migrator runs each migration through `ddl_transaction`, which opens a transaction when `use_transaction?` is true: ```ruby def use_transaction?(migration) !migration.disable_ddl_transaction && connection.supports_ddl_transactions? end ``` `PostgreSQLAdapter#supports_ddl_transactions?` returns `true`. The MySQL adapters inherit the abstract default, `false`, because MySQL issues an **implicit commit** before and after most DDL statements; a transaction around them would not protect anything. How MySQL's DDL behaves internally is MySQL's subject; the Rails consequence is that a MySQL migration runs **statement by statement with no undo**. ## What a failure leaves behind The hotel-reservation team writes, as they did on PostgreSQL: ```ruby class AddChannelToReservations < ActiveRecord::Migration[8.1] def change add_column :reservations, :channel, :string, null: false, default: "direct" add_index :reservations, :channel add_reference :reservations, :partner, foreign_key: true # fails end end ``` Say the foreign key fails because the `partners` table has an incompatible key type (the adapter raises `ActiveRecord::MismatchedForeignKey` for that case). On MySQL: | Step | State after the failure | |---|---| | `add_column :channel` | applied and committed | | `add_index :channel` | applied and committed | | `add_reference :partner` | failed, possibly with the column added but no constraint | | `schema_migrations` row | **not written**; Rails records the version only after `migrate` finishes | Running `bin/rails db:migrate` again starts the migration from the top, and the first statement fails with MySQL's duplicate-column error. The migration is stuck until someone intervenes. `db:rollback` does not help either: it only reverts migrations whose version is recorded. ## Recovering 1. **Read the real schema.** Check the table definition in `bin/rails dbconsole` to see which steps landed. 2. **Choose a direction.** Either undo the applied steps by hand (drop the index, then the column) so the fixed migration can run from a clean state, or finish forward. 3. **Make reruns safe if you go forward.** Rails' schema methods accept guards: `add_column ..., if_not_exists: true`, `add_index ..., if_not_exists: true`, `remove_column ..., if_exists: true`. Fix the failing step, rerun, and let the guarded steps pass over what exists. 4. **Re-dump the schema.** After the migration succeeds, check that `db/schema.rb` matches the database on every environment that saw the failure. ## Preventing it - **One schema change per migration** where a failure would be awkward. A failed single-step migration leaves nothing half done. - **Separate data changes from DDL.** A backfill that fails halfway is just as non-transactional on MySQL once DDL has committed around it; give it its own migration, and its own transaction if it touches many rows. - **Rehearse on a copy** of production-sized data, where foreign-key type mismatches and long locks show up. - **Use guards deliberately**, not everywhere: `if_not_exists:` hides drift between environments if it becomes a habit. - **Know your tooling.** Safety checks for MySQL-specific risks (such as which `ALTER TABLE` forms lock the table) belong to the migration-safety tooling, not to the adapter. ## Checking state before you touch anything - `bin/rails db:migrate:status` lists the migration as **down**, because its version is missing, even though some of its changes are in the database. - The table definition shows what really landed; compare it with `db/schema.rb`, which still describes the state before the migration. - On a shared environment, stop further deploys until the state is fixed, because each deploy that runs `db:migrate` will fail at the same step. ## What does not help - `disable_ddl_transaction!` changes nothing on MySQL, because there was no transaction to disable. - Wrapping the body in `transaction do ... end` yourself cannot roll back committed DDL.
- Why does db:rollback not undo a half-applied MySQL migration in Rails?Rollback reverts the most recent migration whose version is recorded in `schema_migrations`. A migration that failed partway never had its version written, because Rails records it only after `migrate` completes, so rollback targets the previous migration instead. The applied steps have to be undone by hand or skipped on rerun.
- Does disable_ddl_transaction! change anything for a migration on MySQL?No. It tells Rails not to open the migration transaction, but the MySQL adapters never open one, because `supports_ddl_transactions?` is false. It matters on PostgreSQL, for statements such as concurrent index builds that cannot run inside a transaction.
A MySQL migration is like a renovation crew that cements each wall as soon as it is built. If the third wall fails, the first two are already set, and the job sheet still says not started, so the next crew arrives and tries to build wall one again.
- Assumes Rails rolls back a failed MySQL migration like on PostgreSQL
- Runs db:rollback to undo a migration that never recorded its version
- Wraps DDL in a transaction block expecting MySQL to undo it
- Puts schema changes and a large backfill in one MySQL migration
- Adds if_not_exists: to every statement as a permanent habit