Gestionnaire de migrations de base de données

VérifiéPrudence

Gérez les migrations de schéma de base de données avec validation, rollback et automatisation pour PostgreSQL, MySQL et MongoDB.

Spar Skills Guide Bot
DevOpsIntermédiaire
29/08/2026
Claude Code
#database#migrations#schema#sql#rollback

Recommandé pour

Synthèse automatique

Cette skill guide la création, la validation et l'exécution de migrations de schéma de base de données, avec rollback et prise en charge de PostgreSQL, MySQL et MongoDB.

Points forts

  • Couvre le cycle complet : capture du schéma de départ, écriture des migrations UP/DOWN, validation sur staging puis application
  • Inclut des patrons concrets pour la production : expand-contract en zéro downtime et outils de DDL en ligne (pg_repack, gh-ost, pt-online-schema-change) pour les grosses tables
  • Donne les commandes exactes par framework (Flyway, Alembic, Prisma, Knex) et les conventions de nommage des fichiers
  • Impose des garde-fous utiles : colonnes ajoutées nullables puis backfill, idempotence via IF NOT EXISTS, transactions explicites

Limites

  • Suppose un framework de migration déjà installé, une base de staging alignée sur la production et des droits DDL accordés
  • L'accent est mis sur PostgreSQL/MySQL/SQL Server classique ; le volet MongoDB reste très succinct
  • Ne traite pas des cas de rollback impossibles après perte de données (drops destructifs) au-delà d'une recommandation de colonne de sauvegarde
Quand l'utiliser

À utiliser dès qu'il faut ajouter, modifier ou supprimer des objets de schéma en base et produire une migration versionnée avec procédure de rollback.

Quand l'éviter

À éviter pour une simple requête de lecture/écriture applicative ou quand aucune modification de schéma n'est prévue.

Analyse de sécurité

Prudence
Score qualité90/100

This is legitimate database migration guidance and does not contain exfiltration, obfuscation, or safety-disabling behavior. However, it grants database CLI access and repeatedly discusses destructive DDL and production migration operations, so misuse or accidental targeting of production could cause data loss.

Points d'attention
  • •Bash access is scoped to psql/mysql/mongosh but still permits arbitrary SQL/DDL, including DROP, ALTER, and data backfills, against any reachable database.
  • •Instructions include destructive operations such as DROP in rollback and dropping dependent views, without mandatory production safeguards like dry-run, backup verification, or approval gates.
  • •Schema dumps and migration execution may expose production data or credentials; the skill does not define secret handling or environment isolation.
Comment cette analyse est faite

Exemples

Add a column to orders
Create a versioned migration that adds a nullable `status` column to the `orders` table in our Postgres database, backfill it with 'pending', then set NOT NULL. Include the DOWN migration and show how to validate it on staging.
Zero-downtime rename
We need to rename the `users.fullname` column to `users.display_name` on a 20M-row production table without downtime. Walk me through the expand-contract migration steps with Alembic and the SQL for each phase.
Verify migration rollback
Validate migration V20240115_001 on staging: apply UP, confirm the schema, run the DOWN, and check the schema matches schema_before.sql. Report any mismatch.

name: managing-database-migrations description: 'Process use when you need to work with database migrations.

This skill provides schema migration management with comprehensive guidance and automation.

Trigger with phrases like "create migration", "run migrations",

or "manage schema versions".

' allowed-tools: Read, Write, Edit, Grep, Glob, Bash(psql:), Bash(mysql:), Bash(mongosh:*) version: 1.23.0 author: Jeremy Longshore jeremy@intentsolutions.io license: MIT tags:

  • database
  • migration
  • database-migrations compatibility: Designed for Claude Code

Database Migration Manager

Overview

Create, validate, and execute database schema migrations with full rollback support across PostgreSQL, MySQL, and MongoDB.

Prerequisites

  • Database credentials with DDL permissions (CREATE, ALTER, DROP TABLE)
  • Migration framework installed and configured (Flyway, Alembic, Prisma, Knex, or raw SQL versioning)
  • Version control for migration files (Git repository)
  • Access to a staging database matching production schema for testing migrations
  • psql or mysql CLI for executing and verifying migrations
  • Current schema baseline documented or captured via pg_dump --schema-only

Instructions

  1. Capture the current schema state before making changes. Run pg_dump --schema-only -f schema_before.sql (PostgreSQL) or mysqldump --no-data > schema_before.sql (MySQL) to create a reference point.

  2. Define the desired schema change clearly: specify table name, column additions/removals/modifications, constraint changes, and index updates. Document whether the change is additive (safe) or destructive (requires data migration).

  3. Generate a versioned migration file following the framework's naming convention:

    • Flyway: V20240115_001__add_status_column_to_orders.sql
    • Alembic: alembic revision --autogenerate -m "add status column to orders"
    • Prisma: Edit schema.prisma then npx prisma migrate dev --name add_status_to_orders
    • Knex: npx knex migrate:make add_status_to_orders
  4. Write the UP migration (forward change) with these safety practices:

    • Add new columns as nullable first, then backfill, then set NOT NULL
    • Use IF NOT EXISTS for CREATE operations to make migrations idempotent
    • Add explicit transaction wrapping: BEGIN; ... COMMIT;
    • Include comments explaining the business reason for each change
  5. Write the DOWN migration (rollback) that exactly reverses the UP migration. For column additions, the DOWN drops the column. For table renames, the DOWN renames back. For data transformations, the DOWN must restore original data (store it in a backup column or table if needed).

  6. Validate the migration on staging by running the full migration sequence:

    • Apply the UP migration and verify schema matches expectations
    • Run the application test suite against the migrated schema
    • Apply the DOWN migration and verify the schema returns to its original state
    • Re-apply the UP migration to confirm idempotency
  7. For zero-downtime migrations on production, follow the expand-contract pattern:

    • Phase 1 (expand): Add new column/table without removing old ones. Deploy application code that writes to both old and new.
    • Phase 2 (migrate): Backfill new column/table from old data in batches.
    • Phase 3 (contract): Deploy application code that reads only from new. Drop old column/table in a future migration.
  8. Handle large table migrations (>10M rows) with online DDL tools: pg_repack for PostgreSQL, pt-online-schema-change for MySQL, or gh-ost for MySQL. These tools create a shadow table, replicate changes, then swap atomically.

  9. Update the migration history table and verify the migration version matches expectations. Run flyway info or alembic current to confirm.

  10. Document the migration in a changelog with: migration version, description, tables affected, estimated execution time, rollback procedure, and any required application deployments.

Output

  • Migration files (UP and DOWN) in the target framework's format
  • Pre-flight validation script checking prerequisites before migration execution
  • Data backfill scripts for non-nullable column additions on existing tables
  • Rollback runbook with step-by-step instructions for reverting in production
  • Migration changelog entry documenting the change for team reference

Error Handling

| Error | Cause | Solution | |-------|-------|---------| | Migration fails with lock timeout | Long-running queries blocking DDL locks on the target table | Set lock_timeout = '5s' to fail fast; retry during low-traffic period; use pg_repack for lock-free operations | | Column cannot be dropped because of dependent views | Views or materialized views reference the column being removed | Drop or recreate dependent views first; use CASCADE only after verifying all dependents are acceptable to drop | | NOT NULL constraint violation during migration | Existing rows have NULL values in a column being made NOT NULL | Add a backfill step: UPDATE table SET column = default_value WHERE column IS NULL before adding NOT NULL | | Migration version conflict | Two developers created migrations with the same version number | Use timestamp-based versioning; resolve by renaming one migration and re-running | | Rollback fails because data was inserted after UP migration | New data in added columns has no place to go in the old schema | Design rollback to handle new data (backup column, log discarded data); accept that some rollbacks are data-lossy |

Examples

Adding a status enum column to an orders table: Generate a migration that: (1) creates the enum type CREATE TYPE order_status AS ENUM ('pending', 'shipped', 'delivered'), (2) adds column ALTER TABLE orders ADD COLUMN status order_status, (3) backfills UPDATE orders SET status = 'delivered' WHERE shipped_at IS NOT NULL, (4) sets NOT NULL ALTER TABLE orders ALTER COLUMN status SET NOT NULL. Rollback drops the column and enum type.

Splitting a monolith users table into users and profiles: Expand phase adds profiles table and triggers to sync data. Migrate phase copies existing profile data in batches of 10,000 rows. Contract phase drops profile columns from users table after application code is updated.

Renaming a column without downtime: Create a migration that adds the new column, adds a trigger to sync writes between old and new columns, backfills existing data, deploys application code using the new column name, then drops the old column and trigger in a follow-up migration.

Resources

  • Flyway documentation: https://documentation.red-gate.com/fd
  • Alembic tutorial: https://alembic.sqlalchemy.org/en/latest/tutorial.html
  • Prisma Migrate: https://www.prisma.io/docs/orm/prisma-migrate
  • pg_repack (lock-free table rewrite): https://reorg.github.io/pg_repack/
  • gh-ost (GitHub online schema change): https://github.com/github/gh-ost

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/database-migration-manager-mte1ljrq/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

mkdir -p '.skill-downloads/database-migration-manager-mte1ljrq' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/database-migration-manager-mte1ljrq/download' --output '.skill-downloads/database-migration-manager-mte1ljrq/SKILL.md.part' && mv '.skill-downloads/database-migration-manager-mte1ljrq/SKILL.md.part' '.skill-downloads/database-migration-manager-mte1ljrq/SKILL.md'

2. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Environnement déclaré par l’auteur : Designed for Claude Code

Outils déclarés par l’auteur (à vérifier dans votre agent) : Read, Write, Edit, Grep, Glob, Bash(psql:*), Bash(mysql:*), Bash(mongosh:*)

Extrait original : Prerequisites
  • Database credentials with DDL permissions (CREATE, ALTER, DROP TABLE)
  • Migration framework installed and configured (Flyway, Alembic, Prisma, Knex, or raw SQL versioning)
  • Version control for migration files (Git repository)
  • Access to a staging database matching production schema for testing migrations
  • psql or mysql CLI for executing and verifying migrations
  • Current schema baseline documented or captured via pg_dump --schema-only

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.

Claude Code
test -f '.skill-downloads/database-migration-manager-mte1ljrq/SKILL.md' && test -s '.skill-downloads/database-migration-manager-mte1ljrq/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/managing-database-migrations' && cp -R '.skill-downloads/database-migration-manager-mte1ljrq' '.claude/skills/managing-database-migrations'

OpenSkills

OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.

Installation officielle d’OpenSkills
openskills install './.skill-downloads/database-migration-manager-mte1ljrq'

openskills read 'database-migration-manager-mte1ljrq'

La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.

Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.

openskills sync

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/database-migration-manager-mte1ljrq/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires