Przejdź do treści
Biblioteka skilli
Programowanie · Budowanie i kod

rails-safe-migrations

/rails-safe-migrations

Pisze i przegląda migracje Active Record w Rails 8, które można uruchomić podczas obsługi ruchu: indeksy współbieżne, expand and contract i wsadowe backfille w PostgreSQL.

Licencja
MIT
Ostatnia zmiana repozytorium
19.10.2026

Ocena i bezpieczeństwo

100/ 100Klasa: dobry
Format25 / 25
Frontmatter z nazwą i opisem, poprawna nazwa, opis do 1024 znaków, nazwa zgodna z folderem.
Odkrywalność25 / 25
Opis mówi, kiedy użyć skilla, ma sensowną długość i jest w 3. osobie.
Treść35 / 35
Co najmniej 150 słów i do 500 linii, nagłówki, listy kroków, przykłady albo kod.
Higiena15 / 15
Bez zaślepek typu TODO, bez ścieżek Windows, z licencją.
Ryzykobrak sygnałów w skanie
Pliki w paczce
2
Skrypty
0
Komentarze HTML
0
Adresy URL w SKILL.md
0
Przestarzałość

Brak sygnałów. Repozytorium zmienione 19.10.2026, bez odwołań do wycofanych modeli i API.

Licencja

MIT, otwarta: można używać i zmieniać, z zachowaniem informacji o autorze.

Co robi i kiedy

Pisze i przegląda migracje Active Record w Rails 8, które można uruchomić podczas obsługi ruchu: indeksy współbieżne, expand and contract i wsadowe backfille w PostgreSQL.

Oryginalny opis (EN)

Writes and reviews Rails 8 Active Record migrations that can run while the app is serving traffic, using concurrent indexes, unvalidated constraints, ignored_columns, expand and contract steps, and batched backfills. Use when adding or changing a migration on a table with real data, before deploying a schema change, or when reviewing a migration in a pull request. Patterns target PostgreSQL, with MySQL notes.

Jak działa

  1. Steps
  2. Dangerous operations and the safe version
  3. Example: adding an index
  4. Example: removing a column in two deploys
  5. Timeouts
  6. Review checklist
  7. MySQL notes
  8. Tooling
Sekcje z nagłówków SKILL.md, w oryginale · 95 linii, 733 słów
Podgląd SKILL.md
---
name: rails-safe-migrations
description: Writes and reviews Rails 8 Active Record migrations that can run while the app is serving traffic, using concurrent indexes, unvalidated constraints, ignored_columns, expand and contract steps, and batched backfills. Use when adding or changing a migration on a table with real data, before deploying a schema change, or when reviewing a migration in a pull request. Patterns target PostgreSQL, with MySQL notes.
license: MIT
---

# Safe Rails migrations

The app keeps running old code while a migration runs, and for a while after it. Each migration must be safe against both the old code and the new code. The other risk is locking: an `ALTER TABLE` that rewrites or scans a busy table blocks reads and writes until it finishes.

## Steps

1. Read the migration and the size of every table it touches. If a table is small (thousands of rows) and quiet, most of this is optional. Say so, and keep the simple version.
2. Check each operation against the table below. If it's on the list, use the safe version.
3. Split risky changes into separate migrations and deploys. One migration should not both change the schema and backfill it.
4. Set timeouts so a blocked migration fails fast instead of queuing every query behind it.
5. Run `bin/rails db:migrate` and then `bin/rails db:rollback` locally, and check the diff in `db/schema.rb` or `db/structure.sql`.

## Dangerous operations and the safe version

| Operation | Risk | Safe version |
|---|---|---|
| `add_index` on an existing table | Blocks writes while it builds | `algorithm: :concurrently` with `disable_ddl_transaction!` |
| `add_reference` | Builds the index the blocking way | `index: { algorithm: :concurrently }` with `disable_ddl_transaction!` |
| `add_foreign_key` | Scans both tables under lock | `validate: false`, then `validate_foreign_key` in a second migration |
| `change_column_null ..., false` | Full scan under lock | Unvalidated check constraint first, then validate, then set NOT NULL |
| `add_check_constraint` | Full scan under lock | `validate: false`, then `validate_check_constraint` |
| `remove_column` | Old code still selects it and errors | `ignored_columns` first, deploy, then remove |
| `rename_column` / `rename_table` | Old code uses the old name | Expand and contract (add new, write both, backfill, switch reads, drop old) |
| `change_column` type | Usually rewrites the table | Expand and contract with a new column |
| Backfill in the same migration as the `ALTER` | Holds the lock for the whole backfill | Separate migration, batched, outside the DDL transaction |
| Column with a volatile default like `gen_random_uuid()` | Rewrites the table | Add with no default, then `change_column_default`, then backfill |

Full code for each row is in `references/patterns.md` in this skill's folder.

## Example: adding an index

```ruby
class AddIndexToOrdersOnCustomerId < ActiveRecord::Migration[8.1]
  disable_ddl_transaction!

  def change
    add_index :orders, :customer_id, algorithm: :concurrently
  end
end
```

Without `disable_ddl_transaction!`, PostgreSQL refuses to build the index concurrently inside the migration's transaction, and the migration fails. If a concurrent build fails partway, it leaves an invalid index behind. Drop it with `remove_index ..., algorithm: :concurrently` before you retry.

## Example: removing a column in two deploys

```ruby
# Deploy 1: app/models/user.rb
class User < ApplicationRecord
  self.ignored_columns += ["legacy_token"]
end
```

```ruby
# Deploy 2, once deploy 1 is live everywhere
class RemoveLegacyTokenFromUsers < ActiveRecord::Migration[8.1]
  def change
    remove_column :users, :legacy_token, :string
  end
end
```

Then delete the `ignored_columns` line. Passing the type to `remove_column` keeps the migration reversible. If the project uses the strong_migrations gem, wrap the removal in `safety_assured { ... }`.

## Timeouts

Set them per migration, or for the whole app in `config/database.yml`:

```yaml
production:
  variables:
    lock_timeout: 10s
    statement_timeout: 15s
```

Concurrent index builds and validations can take longer than a normal statement. For those migrations, raise `statement_timeout` with `execute "SET statement_timeout = '1h'"` at the start.

## Review checklist

- Every `add_index`, `add_reference` and `remove_index` on an existing table is concurrent, and its migration disables the DDL transaction.
- Foreign keys and check constraints on big tables are added with `validate: false` and validated in a later migration.
- No migration both alters a table and backfills it.
- Removed or renamed columns have an `ignored_columns` step in an earlier deploy.
- Backfills use `in_batches` with `update_all`, not `each` with `save`.
- The migration class uses the app's current version, such as `Migration[8.1]`.
- `down` works, or the migration raises `ActiveRecord::IrreversibleMigration` on purpose.

## MySQL notes

MySQL has no `algorithm: :concurrently`. InnoDB builds most indexes online by default, and DDL is not transactional, so `disable_ddl_transaction!` changes little. Removing and renaming columns still need the `ignored_columns` and expand and contract steps.

## Tooling

The strong_migrations gem (github.com/ankane/strong_migrations) blocks most of the operations above at `db:migrate` time and prints the safe version. Recommend it. Don't add it without asking, since it changes every future migration.
Pliki w paczce (2)
  • SKILL.md 5 KB
  • references/patterns.md 4 KB

Wersje

W bazie nie ma innych skilli o nazwie rails-safe-migrations.

Migawka bazy z 13.11.2026 · wersja paczki 8aa21f6b080d (skrót SHA-256 całej paczki)

Pobrania w ostatnich 30 dniach: 1 · ranking

Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.

Podobne skille

  • 100database-migrations
    Stosuje bezpieczne migracje baz: zmiany tylko do przodu, etapowe zmiany nazw, indeksy współbieżne i partie uzupełniania danych dla PostgreSQL i Prisma.
  • 100database-migrations
    Opisuje bezpieczne, odwracalne wzorce migracji: zmiany tylko do przodu, zmiany nazw bez przestojów, indeksy współbieżne, backfille wsadowe i przepływy dla PostgreSQL, Prisma, Drizzle, Django i golang-migrate.
  • 100django-migrations
    Pisze i przegląda migracje Django bezpieczne do wdrożenia przy działającym starym kodzie: migracje danych z RunPython, backfille partiami, pola non-null i unique, indeksy concurrent w PostgreSQL oraz dwustopniowe usuwanie pól.
  • 100safe-migrations
    Przegląda i pisze migracje bazy bez blokad tabel, w etapach expand i contract dla PostgreSQL i MySQL. Przydaje się przed komendą resetującą lub usuwającą bazę.
  • 100database-migrations
    Planuje i pisze migracje schematu bez przestojów: etapowe zmiany, bezpieczne indeksy, partie uzupełniania danych i plan wycofania.
  • 100migration-review
    Sprawdza migracje PostgreSQL pod kątem blokad, przepisywania tabel i ryzyka utraty danych, a ryzykowne kroki zamienia na bezpieczne sekwencje.

Uwagi i zgłoszenia

Wiadomość trafi do Bartosza Sokolińskiego. Adres e-mail jest potrzebny tylko do odpowiedzi. Szczegóły w polityce prywatności.