[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6D1SRANTA7SCTAY8HENPYMS":3,"skill-same:01M6D1SRANTA7SCTAY8HENPYMS":63},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":35,"linkOnly":36,"markdownContent":37,"markdownBody":38,"frontMatter":39,"refName":40,"commitSha":41,"skillDirectory":42,"forksCount":43,"repositoryHtmlUrl":44,"repositoryHomepageUrl":45,"ownerHtmlUrl":46,"ownerBlogUrl":45,"ownerDescription":47,"updatedAt":48,"install":49,"resources":62},"01M6D1SRANTA7SCTAY8HENPYMS","database-migrations",null,"Changing a live database safely: the project's migration tool, migrations that never get edited once applied, expand and contract for zero downtime, locks to avoid, backfills in batches, data migrations apart from schema changes, testing on a copy, and ordering with deploys. Read before writing any migration.","enowdev\u002Fenowxcli","enowdev","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F179420349?v=4","01M6D1MVX2KC0X3Z9NESE7P22K","Enow Dev.","01M6D1MW1FMZGBDKWAJY4GQX81",67,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fdatabase-migrations\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],"database","database migrations","migrations","testing","writing","ZeRO","data","tool","read","schema","never","migration","project","get","contract","live","2026-11-10 10:12:30",false,"---\nname: database-migrations\ndescription: \"Changing a live database safely: the project's migration tool, migrations that never get edited once applied, expand and contract for zero downtime, locks to avoid, backfills in batches, data migrations apart from schema changes, testing on a copy, and ordering with deploys. Read before writing any migration.\"\n---\n\n# Migrations on live data\n\nThe generated migration: made by the ORM and committed unread, renaming a\ncolumn the running code still reads, adding a NOT NULL column and a foreign\nkey in one step on a table of 40 million rows, building an index without\n`CONCURRENTLY` at noon, and a backfill that updates every row in one\ntransaction. On an empty development database each of these is instant,\nwhich is why they ship; on production each is a lock or an outage. This\nskill is how a schema change reaches a live database without stopping it.\nWhat the schema should be is `database-schema`; the short rules for server\ncode are in `backend-data`.\n\n## 1. The tool, by stack\n\nUse the project's tool. Never tables made by hand, never a schema sync\n(`prisma db push`, `drizzle-kit push`, TypeORM `synchronize: true`,\nSequelize `sync({ alter: true })`) against a database anyone shares.\n\n| Stack | Create | Apply | Status, undo |\n|---|---|---|---|\n| Prisma | `prisma migrate dev --create-only --name add_status` | `prisma migrate deploy` | `prisma migrate status`; no down files |\n| Drizzle Kit | `drizzle-kit generate` | `drizzle-kit migrate` | `drizzle-kit check` |\n| Alembic | `alembic revision --autogenerate -m \"add status\"` | `alembic upgrade head` | `alembic current`, `alembic downgrade -1` |\n| Django | `python manage.py makemigrations` | `python manage.py migrate` | `showmigrations`, `migrate app 0041` |\n| Rails | `bin\u002Frails g migration AddStatusToOrders status:string` | `bin\u002Frails db:migrate` | `db:migrate:status`, `db:rollback` |\n| Laravel | `php artisan make:migration add_status_to_orders_table` | `php artisan migrate --force` | `migrate:status`, `migrate:rollback` |\n| sqlx | `sqlx migrate add -r add_status` | `sqlx migrate run` | `sqlx migrate info`, `sqlx migrate revert` |\n| golang-migrate | `migrate create -ext sql -dir db\u002Fmigrations -seq add_status` | `migrate -path db\u002Fmigrations -database \"$DATABASE_URL\" up` | `version`, `down 1`, `force N` after a failure |\n| goose | `goose create add_status sql` | `goose up` | `goose status`, `goose down` |\n| Atlas | `atlas migrate diff add_status` | `atlas migrate apply` | `atlas migrate status`, `atlas migrate lint` |\n| Flyway | a `V7__add_status.sql` file | `flyway migrate` | `flyway info`, `flyway validate` |\n| EF Core | `dotnet ef migrations add AddStatus` | `dotnet ef database update` or a script (`migrations script --idempotent`) | `dotnet ef migrations list` |\n\nA generated migration is a draft. Read the SQL it will run\n(`python manage.py sqlmigrate app 0042`, `alembic upgrade head --sql`,\n`php artisan migrate --pretend`, the `.sql` file Prisma or Drizzle wrote) and\nfix what generators get wrong: a rename seen as drop plus add (the data is\nlost), a type change that rewrites the table, a missing `CONCURRENTLY`, an\nindex duplicating one that exists, a default set in the ORM but not in the\ndatabase.\n\n## 2. Rules\n\n- A migration that ran anywhere shared (staging, production, main) is never\n  edited or deleted; a fix is a new migration. Flyway and sqlx refuse a\n  changed checksum, Prisma's `migrate dev` flags it, other tools let\n  environments silently diverge.\n- One concern per migration, named for it (`add_status_to_orders`); schema\n  and data changes apart.\n- A down migration where the change can be undone; where it cannot (a\n  dropped column's data), the down raises with the reason.\n- Migrations run once per deploy as their own step (a release or pre-deploy\n  command, a Kubernetes Job), not by every instance at boot. Prisma, Rails\n  and Flyway take a lock so a second runner waits; Laravel needs\n  `migrate --isolated`; Django takes none.\n- Postgres and SQLite run DDL inside the migration's transaction and roll it\n  back whole on error. MySQL commits each DDL statement on its own, so a\n  failed migration of three statements leaves some applied: one DDL\n  statement per migration there.\n\n## 3. Order with deploys\n\nDuring a rolling deploy old and new code run together on one schema, so\nevery migration must work with both versions.\n\n| Change | Order |\n|---|---|\n| Additive: table, nullable column, index | Migrate, then deploy the code that uses it |\n| Destructive: drop a column or table | Deploy code that no longer uses it, then drop in a later release |\n| Rename, type change | Expand and contract over several releases (section 4) |\n| A new NOT NULL or CHECK rule | Code writes valid values everywhere, backfill, then the constraint |\n\nORMs that cache the column list fail when a column vanishes under them: tell\nthe ORM first (Rails `self.ignored_columns += [\"total\"]`), deploy, then drop.\n\n## 4. Expand and contract\n\nReplacing `orders.total` (numeric) with `orders.total_cents` (bigint)\nwithout downtime:\n\n1. **Expand**: add `total_cents bigint`, nullable, no default. Instant.\n2. **Write both**: deploy code that writes both columns on every insert and\n   update (or a trigger that fills the new from the old).\n3. **Backfill** the existing rows in batches (section 8).\n4. **Constrain**: NOT NULL through a validated CHECK, indexes built\n   concurrently (section 5).\n5. **Read the new column**; deploy.\n6. **Stop writing the old one**; deploy.\n7. **Contract**: drop `total` in a later release, after a backup.\n\nEach step is its own deploy and can stop or roll back on its own. A table\nrename works the same way, or with a view under the old name during the\nmove.\n\n## 5. Postgres locks\n\nMost `ALTER TABLE` forms take an ACCESS EXCLUSIVE lock. Even an instant one\nwaits for every running query on the table, and while it waits every new\nquery queues behind it: a five-minute report plus an instant ALTER is a\nfive-minute outage. Every migration on a live table starts with:\n\n```sql\nSET lock_timeout = '5s';          -- give up instead of queueing traffic behind us\nSET statement_timeout = '15min';  -- what the step needs, never unbounded\n```\n\nand the deploy retries a step that timed out, a few times, with a pause.\n\n| Operation | What happens | Do instead |\n|---|---|---|\n| `ADD COLUMN`, nullable or with a constant default | Catalog only (PG 11+) | Fine, with `lock_timeout` |\n| `ADD COLUMN ... DEFAULT gen_random_uuid()` (volatile) | Rewrites the table | Add nullable, backfill, then set the default |\n| `SET NOT NULL` | Scans the table under the lock | `CHECK (c IS NOT NULL) NOT VALID`, `VALIDATE`, `SET NOT NULL` (PG 12+ skips the scan), drop the CHECK |\n| `ADD FOREIGN KEY` | Checks every row, locking both tables | `ADD CONSTRAINT ... NOT VALID`, then `VALIDATE CONSTRAINT` |\n| `ADD CHECK` | Scans under the lock | `NOT VALID`, then `VALIDATE CONSTRAINT` |\n| `ADD UNIQUE` | Builds the index under the lock | `CREATE UNIQUE INDEX CONCURRENTLY`, then `ADD CONSTRAINT ... UNIQUE USING INDEX` |\n| `CREATE INDEX` | Blocks writes for the whole build | `CREATE INDEX CONCURRENTLY`, outside a transaction |\n| `ALTER COLUMN TYPE` | Rewrites table and indexes | Expand and contract; `varchar(n)` to a larger `n` or to `text` is catalog only |\n| `RENAME` column or table | Instant, breaks running code | Expand and contract |\n| `DROP COLUMN` | Instant | Only after the code stopped using it |\n| `VACUUM FULL`, `CLUSTER` | Rewrite under the exclusive lock | `pg_repack` |\n\n`VALIDATE CONSTRAINT` takes a SHARE UPDATE EXCLUSIVE lock, so reads and\nwrites carry on while it scans. Building concurrently in each tool:\n\n- Rails: `disable_ddl_transaction!` with `add_index ..., algorithm: :concurrently`.\n- Django: `AddIndexConcurrently` in a migration with `atomic = False`.\n- Alembic: `op.create_index(..., postgresql_concurrently=True)` inside\n  `with op.get_context().autocommit_block():`.\n- SQL-file tools: a migration holding only that statement, marked to run\n  outside a transaction (goose: `-- +goose NO TRANSACTION`).\n- A failed concurrent build leaves an invalid index. Find it with\n  `SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid;`, drop it\n  with `DROP INDEX CONCURRENTLY`, and build again.\n\n## 6. MySQL\n\n- Name the algorithm, so MySQL refuses instead of silently copying the\n  table: `ALTER TABLE orders ADD COLUMN note TEXT, ALGORITHM=INSTANT;` and\n  `ALTER TABLE orders ADD INDEX idx_orders_status (status), ALGORITHM=INPLACE, LOCK=NONE;`.\n- `INSTANT` adds or drops a column at any position from 8.0.29, up to 64\n  row versions per table; after that the table needs a rebuild.\n- Metadata locks: DDL waits behind any open transaction that touched the\n  table, and everything queues behind the DDL; `lock_wait_timeout` defaults\n  to a year. Run `SET SESSION lock_wait_timeout = 5;` first.\n- Type changes and anything else that copies: gh-ost (reads the binlog,\n  needs `binlog_format=ROW`) or pt-online-schema-change (triggers) on large\n  tables, or deploy requests on PlanetScale and Vitess (`database-mysql`).\n\n## 7. SQLite\n\nDDL is transactional, but `ALTER TABLE` only adds, renames (3.25+) and drops\n(3.35+) columns. A type, constraint or foreign key change is the table\nrebuild in `database-sqlite`. It locks the whole database while it runs,\nusually for milliseconds.\n\n## 8. Backfills\n\n- Outside the schema migration: a script or job that can run for hours,\n  pause and resume, not one migration transaction.\n- By primary key range, each batch its own short transaction, idempotent (it\n  touches only rows not yet done), progress logged with the last id:\n\n```sql\n-- $1 walks from min(id) to max(id) in steps of 5000\nUPDATE orders\nSET total_cents = round(total * 100)\nWHERE id >= $1 AND id \u003C $1 + 5000\n  AND total_cents IS NULL;\n```\n\n- 1,000 to 10,000 rows per batch, sized so each takes well under a second,\n  with 50 to 500ms between batches; watch replica lag and pause when it\n  grows.\n- Count before and after: the rows still NULL reach 0 before the NOT NULL\n  step.\n- Never one `UPDATE` over the whole table: it holds its row locks until the\n  end, leaves a dead copy of every row in Postgres, and floods the replicas.\n\n## 9. Data migrations\n\n- A change to the data (splitting a name, moving settings into a table) is\n  its own migration or script, apart from the schema change, with the count\n  of rows expected to change and a check of the counts afterwards.\n- Never the app's current models inside a migration: they change later and\n  the old migration breaks. Use SQL, `apps.get_model()` in Django's\n  `RunPython`, or a small model class defined inside the migration.\n- Keep the old data until the new is verified.\n\n## 10. Destructive changes\n\n- Say so in the report before it runs: which table or column, how many\n  rows, whether the down migration can bring them back (usually not).\n- Back up what is dropped\n  (`pg_dump -Fc -t orders_legacy -f orders_legacy.dump \"$DATABASE_URL\"`) and\n  record where the file is.\n- Keep the old column or table through one release after the code stopped\n  using it, then drop it.\n\n## 11. Testing a migration\n\n- Up, down, up on a scratch database: it catches a down that does not work\n  and an up that cannot run twice.\n- In CI, from empty to head, plus a check that models and migrations agree:\n  `python manage.py makemigrations --check --dry-run`, `alembic check`,\n  `prisma migrate diff ... --exit-code`, `atlas migrate lint`.\n- For a large table, on a restored and anonymised copy: time it, and watch\n  its locks from a second session:\n\n```sql\nSELECT a.pid, l.mode, l.granted, a.wait_event_type, left(a.query, 60)\nFROM pg_locks l JOIN pg_stat_activity a USING (pid)\nWHERE l.relation = 'orders'::regclass;\n```\n\n- Linters that know the dangerous forms: strong_migrations (Rails), squawk\n  (`squawk migrations\u002F*.sql` for Postgres SQL), django-migration-linter,\n  `atlas migrate lint`.\n\n## Check it\n\n- The new migration is the only change in the migrations folder.\n- Up, down and up pass on a scratch database, and the tests pass after.\n- The SQL was read: `lock_timeout` set; indexes built concurrently;\n  constraints added `NOT VALID` then validated; no rename or type change of a\n  live column in one step; no backfill inside.\n- For a large table, the duration and locks measured on a copy are in the\n  report; if no copy was available, the report says so.\n- Destructive steps are named in the report with the backup's location.\n\n## Avoid\n\nEditing an applied migration; `db push` or `synchronize` against a shared\ndatabase; a generated migration committed unread; renaming a column the\nrunning code reads; dropping before the code stopped reading; `CREATE INDEX`\nwithout `CONCURRENTLY` on a live Postgres table; foreign keys and NOT NULL\nvalidated under the lock; ALTER with no `lock_timeout`; a backfill of every\nrow in one transaction; data and schema changes in one migration; app models\nimported into migrations; every instance migrating at boot; several DDL\nstatements in one MySQL migration.\n","# Migrations on live data\n\nThe generated migration: made by the ORM and committed unread, renaming a\ncolumn the running code still reads, adding a NOT NULL column and a foreign\nkey in one step on a table of 40 million rows, building an index without\n`CONCURRENTLY` at noon, and a backfill that updates every row in one\ntransaction. On an empty development database each of these is instant,\nwhich is why they ship; on production each is a lock or an outage. This\nskill is how a schema change reaches a live database without stopping it.\nWhat the schema should be is `database-schema`; the short rules for server\ncode are in `backend-data`.\n\n## 1. The tool, by stack\n\nUse the project's tool. Never tables made by hand, never a schema sync\n(`prisma db push`, `drizzle-kit push`, TypeORM `synchronize: true`,\nSequelize `sync({ alter: true })`) against a database anyone shares.\n\n| Stack | Create | Apply | Status, undo |\n|---|---|---|---|\n| Prisma | `prisma migrate dev --create-only --name add_status` | `prisma migrate deploy` | `prisma migrate status`; no down files |\n| Drizzle Kit | `drizzle-kit generate` | `drizzle-kit migrate` | `drizzle-kit check` |\n| Alembic | `alembic revision --autogenerate -m \"add status\"` | `alembic upgrade head` | `alembic current`, `alembic downgrade -1` |\n| Django | `python manage.py makemigrations` | `python manage.py migrate` | `showmigrations`, `migrate app 0041` |\n| Rails | `bin\u002Frails g migration AddStatusToOrders status:string` | `bin\u002Frails db:migrate` | `db:migrate:status`, `db:rollback` |\n| Laravel | `php artisan make:migration add_status_to_orders_table` | `php artisan migrate --force` | `migrate:status`, `migrate:rollback` |\n| sqlx | `sqlx migrate add -r add_status` | `sqlx migrate run` | `sqlx migrate info`, `sqlx migrate revert` |\n| golang-migrate | `migrate create -ext sql -dir db\u002Fmigrations -seq add_status` | `migrate -path db\u002Fmigrations -database \"$DATABASE_URL\" up` | `version`, `down 1`, `force N` after a failure |\n| goose | `goose create add_status sql` | `goose up` | `goose status`, `goose down` |\n| Atlas | `atlas migrate diff add_status` | `atlas migrate apply` | `atlas migrate status`, `atlas migrate lint` |\n| Flyway | a `V7__add_status.sql` file | `flyway migrate` | `flyway info`, `flyway validate` |\n| EF Core | `dotnet ef migrations add AddStatus` | `dotnet ef database update` or a script (`migrations script --idempotent`) | `dotnet ef migrations list` |\n\nA generated migration is a draft. Read the SQL it will run\n(`python manage.py sqlmigrate app 0042`, `alembic upgrade head --sql`,\n`php artisan migrate --pretend`, the `.sql` file Prisma or Drizzle wrote) and\nfix what generators get wrong: a rename seen as drop plus add (the data is\nlost), a type change that rewrites the table, a missing `CONCURRENTLY`, an\nindex duplicating one that exists, a default set in the ORM but not in the\ndatabase.\n\n## 2. Rules\n\n- A migration that ran anywhere shared (staging, production, main) is never\n  edited or deleted; a fix is a new migration. Flyway and sqlx refuse a\n  changed checksum, Prisma's `migrate dev` flags it, other tools let\n  environments silently diverge.\n- One concern per migration, named for it (`add_status_to_orders`); schema\n  and data changes apart.\n- A down migration where the change can be undone; where it cannot (a\n  dropped column's data), the down raises with the reason.\n- Migrations run once per deploy as their own step (a release or pre-deploy\n  command, a Kubernetes Job), not by every instance at boot. Prisma, Rails\n  and Flyway take a lock so a second runner waits; Laravel needs\n  `migrate --isolated`; Django takes none.\n- Postgres and SQLite run DDL inside the migration's transaction and roll it\n  back whole on error. MySQL commits each DDL statement on its own, so a\n  failed migration of three statements leaves some applied: one DDL\n  statement per migration there.\n\n## 3. Order with deploys\n\nDuring a rolling deploy old and new code run together on one schema, so\nevery migration must work with both versions.\n\n| Change | Order |\n|---|---|\n| Additive: table, nullable column, index | Migrate, then deploy the code that uses it |\n| Destructive: drop a column or table | Deploy code that no longer uses it, then drop in a later release |\n| Rename, type change | Expand and contract over several releases (section 4) |\n| A new NOT NULL or CHECK rule | Code writes valid values everywhere, backfill, then the constraint |\n\nORMs that cache the column list fail when a column vanishes under them: tell\nthe ORM first (Rails `self.ignored_columns += [\"total\"]`), deploy, then drop.\n\n## 4. Expand and contract\n\nReplacing `orders.total` (numeric) with `orders.total_cents` (bigint)\nwithout downtime:\n\n1. **Expand**: add `total_cents bigint`, nullable, no default. Instant.\n2. **Write both**: deploy code that writes both columns on every insert and\n   update (or a trigger that fills the new from the old).\n3. **Backfill** the existing rows in batches (section 8).\n4. **Constrain**: NOT NULL through a validated CHECK, indexes built\n   concurrently (section 5).\n5. **Read the new column**; deploy.\n6. **Stop writing the old one**; deploy.\n7. **Contract**: drop `total` in a later release, after a backup.\n\nEach step is its own deploy and can stop or roll back on its own. A table\nrename works the same way, or with a view under the old name during the\nmove.\n\n## 5. Postgres locks\n\nMost `ALTER TABLE` forms take an ACCESS EXCLUSIVE lock. Even an instant one\nwaits for every running query on the table, and while it waits every new\nquery queues behind it: a five-minute report plus an instant ALTER is a\nfive-minute outage. Every migration on a live table starts with:\n\n```sql\nSET lock_timeout = '5s';          -- give up instead of queueing traffic behind us\nSET statement_timeout = '15min';  -- what the step needs, never unbounded\n```\n\nand the deploy retries a step that timed out, a few times, with a pause.\n\n| Operation | What happens | Do instead |\n|---|---|---|\n| `ADD COLUMN`, nullable or with a constant default | Catalog only (PG 11+) | Fine, with `lock_timeout` |\n| `ADD COLUMN ... DEFAULT gen_random_uuid()` (volatile) | Rewrites the table | Add nullable, backfill, then set the default |\n| `SET NOT NULL` | Scans the table under the lock | `CHECK (c IS NOT NULL) NOT VALID`, `VALIDATE`, `SET NOT NULL` (PG 12+ skips the scan), drop the CHECK |\n| `ADD FOREIGN KEY` | Checks every row, locking both tables | `ADD CONSTRAINT ... NOT VALID`, then `VALIDATE CONSTRAINT` |\n| `ADD CHECK` | Scans under the lock | `NOT VALID`, then `VALIDATE CONSTRAINT` |\n| `ADD UNIQUE` | Builds the index under the lock | `CREATE UNIQUE INDEX CONCURRENTLY`, then `ADD CONSTRAINT ... UNIQUE USING INDEX` |\n| `CREATE INDEX` | Blocks writes for the whole build | `CREATE INDEX CONCURRENTLY`, outside a transaction |\n| `ALTER COLUMN TYPE` | Rewrites table and indexes | Expand and contract; `varchar(n)` to a larger `n` or to `text` is catalog only |\n| `RENAME` column or table | Instant, breaks running code | Expand and contract |\n| `DROP COLUMN` | Instant | Only after the code stopped using it |\n| `VACUUM FULL`, `CLUSTER` | Rewrite under the exclusive lock | `pg_repack` |\n\n`VALIDATE CONSTRAINT` takes a SHARE UPDATE EXCLUSIVE lock, so reads and\nwrites carry on while it scans. Building concurrently in each tool:\n\n- Rails: `disable_ddl_transaction!` with `add_index ..., algorithm: :concurrently`.\n- Django: `AddIndexConcurrently` in a migration with `atomic = False`.\n- Alembic: `op.create_index(..., postgresql_concurrently=True)` inside\n  `with op.get_context().autocommit_block():`.\n- SQL-file tools: a migration holding only that statement, marked to run\n  outside a transaction (goose: `-- +goose NO TRANSACTION`).\n- A failed concurrent build leaves an invalid index. Find it with\n  `SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid;`, drop it\n  with `DROP INDEX CONCURRENTLY`, and build again.\n\n## 6. MySQL\n\n- Name the algorithm, so MySQL refuses instead of silently copying the\n  table: `ALTER TABLE orders ADD COLUMN note TEXT, ALGORITHM=INSTANT;` and\n  `ALTER TABLE orders ADD INDEX idx_orders_status (status), ALGORITHM=INPLACE, LOCK=NONE;`.\n- `INSTANT` adds or drops a column at any position from 8.0.29, up to 64\n  row versions per table; after that the table needs a rebuild.\n- Metadata locks: DDL waits behind any open transaction that touched the\n  table, and everything queues behind the DDL; `lock_wait_timeout` defaults\n  to a year. Run `SET SESSION lock_wait_timeout = 5;` first.\n- Type changes and anything else that copies: gh-ost (reads the binlog,\n  needs `binlog_format=ROW`) or pt-online-schema-change (triggers) on large\n  tables, or deploy requests on PlanetScale and Vitess (`database-mysql`).\n\n## 7. SQLite\n\nDDL is transactional, but `ALTER TABLE` only adds, renames (3.25+) and drops\n(3.35+) columns. A type, constraint or foreign key change is the table\nrebuild in `database-sqlite`. It locks the whole database while it runs,\nusually for milliseconds.\n\n## 8. Backfills\n\n- Outside the schema migration: a script or job that can run for hours,\n  pause and resume, not one migration transaction.\n- By primary key range, each batch its own short transaction, idempotent (it\n  touches only rows not yet done), progress logged with the last id:\n\n```sql\n-- $1 walks from min(id) to max(id) in steps of 5000\nUPDATE orders\nSET total_cents = round(total * 100)\nWHERE id >= $1 AND id \u003C $1 + 5000\n  AND total_cents IS NULL;\n```\n\n- 1,000 to 10,000 rows per batch, sized so each takes well under a second,\n  with 50 to 500ms between batches; watch replica lag and pause when it\n  grows.\n- Count before and after: the rows still NULL reach 0 before the NOT NULL\n  step.\n- Never one `UPDATE` over the whole table: it holds its row locks until the\n  end, leaves a dead copy of every row in Postgres, and floods the replicas.\n\n## 9. Data migrations\n\n- A change to the data (splitting a name, moving settings into a table) is\n  its own migration or script, apart from the schema change, with the count\n  of rows expected to change and a check of the counts afterwards.\n- Never the app's current models inside a migration: they change later and\n  the old migration breaks. Use SQL, `apps.get_model()` in Django's\n  `RunPython`, or a small model class defined inside the migration.\n- Keep the old data until the new is verified.\n\n## 10. Destructive changes\n\n- Say so in the report before it runs: which table or column, how many\n  rows, whether the down migration can bring them back (usually not).\n- Back up what is dropped\n  (`pg_dump -Fc -t orders_legacy -f orders_legacy.dump \"$DATABASE_URL\"`) and\n  record where the file is.\n- Keep the old column or table through one release after the code stopped\n  using it, then drop it.\n\n## 11. Testing a migration\n\n- Up, down, up on a scratch database: it catches a down that does not work\n  and an up that cannot run twice.\n- In CI, from empty to head, plus a check that models and migrations agree:\n  `python manage.py makemigrations --check --dry-run`, `alembic check`,\n  `prisma migrate diff ... --exit-code`, `atlas migrate lint`.\n- For a large table, on a restored and anonymised copy: time it, and watch\n  its locks from a second session:\n\n```sql\nSELECT a.pid, l.mode, l.granted, a.wait_event_type, left(a.query, 60)\nFROM pg_locks l JOIN pg_stat_activity a USING (pid)\nWHERE l.relation = 'orders'::regclass;\n```\n\n- Linters that know the dangerous forms: strong_migrations (Rails), squawk\n  (`squawk migrations\u002F*.sql` for Postgres SQL), django-migration-linter,\n  `atlas migrate lint`.\n\n## Check it\n\n- The new migration is the only change in the migrations folder.\n- Up, down and up pass on a scratch database, and the tests pass after.\n- The SQL was read: `lock_timeout` set; indexes built concurrently;\n  constraints added `NOT VALID` then validated; no rename or type change of a\n  live column in one step; no backfill inside.\n- For a large table, the duration and locks measured on a copy are in the\n  report; if no copy was available, the report says so.\n- Destructive steps are named in the report with the backup's location.\n\n## Avoid\n\nEditing an applied migration; `db push` or `synchronize` against a shared\ndatabase; a generated migration committed unread; renaming a column the\nrunning code reads; dropping before the code stopped reading; `CREATE INDEX`\nwithout `CONCURRENTLY` on a live Postgres table; foreign keys and NOT NULL\nvalidated under the lock; ALTER with no `lock_timeout`; a backfill of every\nrow in one transaction; data and schema changes in one migration; app models\nimported into migrations; every instance migrating at boot; several DDL\nstatements in one MySQL migration.\n",{"name":5,"description":7},"main","38293fe1b096e6bf3646c7344c38786ed688f464","crates\u002Fenowx-core\u002Fskills\u002Fdatabase-migrations",21,"https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli","https:\u002F\u002Fenowx.ai","https:\u002F\u002Fgithub.com\u002Fenowdev","Pretending to be a Developer","2026-10-06 02:05:35",{"source":8,"skillName":5,"commands":50,"prompt":60,"zipAvailable":61},[51,54,57],{"tool":52,"command":53},"npx","npx skills add enowdev\u002Fenowxcli --skill database-migrations",{"tool":55,"command":56},"bunx","bunx skills add enowdev\u002Fenowxcli --skill database-migrations",{"tool":58,"command":59},"pnpm","pnpm dlx skills add enowdev\u002Fenowxcli --skill database-migrations","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fdatabase-migrations\u002FSKILL.md",true,[],[64,74,90,103,124,143],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":35},"01M6D2HQYSQD9N7MTNDT4A7CBM","demo-skill","Project-scope demo skill for tests.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fworkspace\u002F.agents\u002Fskills\u002Fdemo-skill\u002FSKILL.md",[],[71,72,73,31,27],"demo skill","demo","tests",{"skillNo":75,"name":23,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":35},"01M6D2HM0GCPM0TM2HPG9HHR2R","Writing words people read: the specific thing instead of claims, words to drop, sentences, interface copy (buttons, labels, errors, empty states, confirmations), page copy, notifications and emails, alt text and link text, numbers and dates, words that translate well, documentation and voice. Read before writing a page's copy, an interface's text or a document.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fwriting\u002FSKILL.md",[],[23,80,81,82,83,84,27,85,86,87,88,89],"text","emails","empty","drop","document","page","voice","notifications","documentation","translate",{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":35},"01M6D2HG07YS49NM196Q0R3AZ8","ui","Designing or restyling an interface: direction, layout, type, colour, icons, components, states, responsive behaviour. Read before building a page, a screen or a set of components.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui\u002FSKILL.md",[],[92,97,98,99,100,85,101,27,102],"icons","components","SET","responsive","layout","before building",{"skillNo":104,"name":105,"nameZh":6,"description":106,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":35},"01M6D2HB59HZHWG1RYZDV4SJ91","ui-themes","Light and dark themes, and colour that holds in both: tokens with a value per theme, and what each kind of content needs to stay visible (icons, SVG drawings and line art, logos, photos, screenshots, charts, code, maps, borders, shadows, focus, form controls), switching without a flash, and checking both. Read before building a second theme or a theme toggle, and before any drawing, logo or chart on a page that has two themes.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui-themes\u002FSKILL.md",[],[92,110,111,112,113,114,115,116,117,27,102,118,85,119,120,121,97,122,123],"ui themes","switching","photos","tokens","drawing","focus","maps","Art","flash","code","Charts","content","screenshots","logo",{"skillNo":125,"name":126,"nameZh":6,"description":127,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":128,"categories":129,"keywords":130,"publishedAt":35},"01M6D2H5R5KRAE524C8QX0T7Q0","ui-structure","Structure before styling: the blueprint written before any interface code (the screen's job, the regions its kind of page needs, their order and why, the layout skeleton in numbers, the components and their states), the anatomy and order of a homepage, a dashboard, a list, a detail page, settings, a form, sign-in, pricing, docs, an article and a checkout, and how to turn the blueprint into code (tokens, layout primitives, components, sections, page). Read first, before building or rebuilding any page or screen.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui-structure\u002FSKILL.md",[],[131,92,132,98,133,134,119,135,136,137,101,113,138,139,140,27,102,85,141,142],"structure","ui structure","pricing","dashboard","Blueprint","article","anatomy","styling","primitives","list","why","how",{"skillNo":144,"name":145,"nameZh":6,"description":146,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":147,"categories":148,"keywords":149,"publishedAt":35},"01M6D2H0ZZBJG77MBGPZHA6MWD","ui-stack-vue","Building interfaces in Vue 3 and Nuxt: project layout, script setup with typed defineProps, defineEmits and defineModel, attribute fallthrough, slots and scoped slots, template refs, ref, reactive and computed, watch versus watchEffect, composables and VueUse, provide and inject, Pinia, keyed v-for, transitions, Nuxt 4 (app directory, pages, layouts, useFetch and useAsyncData keys, $fetch in handlers, server routes, runtime config, useSeoMeta, NuxtImg, middleware), VeeValidate forms, Reka UI and Nuxt UI, testing, vue-tsc, and the traps. Read when the project uses Vue or Nuxt.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui-stack-vue\u002FSKILL.md",[],[92,150,151,152,153,154,155,156,101,31,157,158,27,159,160,161,162,163,164,22],"vue","stack","ui stack vue","forms","pages","watch","runtime","transitions","fetch","pinia","nuxt","template","server","config","directory"]