Versionnement de schéma

VérifiéPrudence

Gérer le versionnement de schéma de base de données avec fichiers de migration, rollback automatisé et intégration CI/CD.

Spar Skills Guide Bot
DeveloppementIntermédiaire
27/07/2026
Claude CodeCursorWindsurfCopilotCodex
#database#migrations#schema-versioning#rollback#ci-cd

Recommandé pour

Synthèse automatique

Cette compétence met en place un flux de versionnement du schéma de base de données : génération de fichiers de migration horodatés, tests sur une base shadow, intégration des contrôles en CI/CD et procédures de rollback.

Points forts

  • Couvre plusieurs outils de migration (Knex, Prisma, TypeORM, Flyway, Alembic) sans verrouillage fournisseur
  • Inclut un script de rollback concret qui capture l'état avant/après pour l'audit
  • Propose une base shadow via Docker et un workflow de test (apply, rollback, re-apply) vérifiant la réversibilité
  • Détaille l'intégration CI/CD avec un service PostgreSQL dans GitHub Actions

Limites

  • L'exemple de workflow CI/CD est tronqué dans le fichier fourni
  • Ne traite pas des migrations de données complexes ni des cas de rollback destructif
  • Suppose une maîtrise préalable de l'outil de migration et un environnement Docker disponible
Quand l'utiliser

À utiliser lorsqu'il faut versionner des changements de schéma, générer des migrations à partir de diffs ou sécuriser un déploiement avec un rollback fiable.

Quand l'éviter

À éviter pour des bases NoSQL sans migrations versionnées ou lorsqu'aucune base shadow ne peut être provisionnée pour tester les migrations.

Analyse de sécurité

Prudence
Score qualité84/100

The skill is documentation for database migration workflows. It does not exfiltrate data, download remote payloads, obfuscate commands, or disable safety. It does use powerful tools (bash, docker, npx) and includes rollback logic that drops tables, which is legitimate but warrants a caution rating rather than safe, since data-destroying commands exist and no allowed-tools are declared.

Points d'attention
  • •Instructions invoke bash scripts, docker/compose, and npx migration commands even though no allowed-tools are declared, so an agent would need shell/docker access to follow them
  • •Includes a rollback.sh script and migrate:rollback / dropTable operations that can delete schema and data; these are intentional and scoped to a shadow DB but still carry destructive potential if pointed at the wrong DATABASE_URL/ENVIRONMENT
  • •docker-compose snippet exposes a hardcoded local password (POSTGRES_PASSWORD: shadow_test) and port mapping — test-only and low risk, but a weak default to copy into real environments
Comment cette analyse est faite

Exemples

Add an orders table
I changed my data model to add an orders table. Generate a timestamped migration file, test it against a shadow database, and verify it rolls back cleanly.
Set up rollback for a failed deploy
My last production deployment failed after applying two migrations. Write a rollback script that reverts the last two migrations and logs the before/after schema version.
Add migration checks to CI
Add a GitHub Actions job that spins up a PostgreSQL service and runs my migrations up and down to catch broken schema changes before merge.

name: schema-versioning description: >- Set up and manage database schema versioning with migration files, automated rollback capabilities, and CI/CD integration. Use when you need to version database changes, generate migration files from schema diffs, safely roll back failed deployments, or audit schema history. Trigger words: migration, schema change, rollback, database versioning, ALTER TABLE, Prisma migrate, Knex migrations, Flyway, Liquibase. license: Apache-2.0 compatibility: "PostgreSQL 14+, MySQL 8+, or SQLite 3.35+. Node.js 18+ or Python 3.10+." metadata: author: terminal-skills version: "1.0.0" category: development tags: ["database", "migrations", "schema", "rollback"]

Schema Versioning

Overview

This skill helps you establish a reliable database schema versioning workflow: generating timestamped migration files, testing them against a shadow database, integrating schema checks into CI/CD, and rolling back safely when deployments fail. It works with any migration tool (Prisma, Knex, TypeORM, Flyway, Alembic) and focuses on patterns rather than vendor lock-in.

Instructions

1. Initialize migration infrastructure

Set up the migration directory structure and configuration:

# For Knex.js
npx knex init
npx knex migrate:make initial_schema

# For Prisma
npx prisma init
npx prisma migrate dev --name initial_schema

# For Alembic (Python)
alembic init migrations
alembic revision --autogenerate -m "initial_schema"

Create a shadow database for testing migrations before applying to production:

# docker-compose.shadow-db.yml
services:
  shadow-db:
    image: postgres:16
    environment:
      POSTGRES_DB: app_shadow
      POSTGRES_PASSWORD: shadow_test
    ports:
      - "5433:5432"

2. Generate migration files from schema changes

When models change, generate the migration diff:

// Knex migration example: 20250217_add_orders_table.ts
import { Knex } from "knex";

export async function up(knex: Knex): Promise<void> {
  await knex.schema.createTable("orders", (table) => {
    table.uuid("id").primary().defaultTo(knex.fn.uuid());
    table.uuid("user_id").notNullable().references("id").inTable("users");
    table.decimal("total", 10, 2).notNullable();
    table.enum("status", ["pending", "paid", "shipped", "cancelled"]).defaultTo("pending");
    table.timestamps(true, true);
    table.index(["user_id", "status"]);
  });
}

export async function down(knex: Knex): Promise<void> {
  await knex.schema.dropTableIfExists("orders");
}

3. Test migrations safely

Always test against a shadow database before production:

# Apply all pending migrations to shadow database
DATABASE_URL="postgres://localhost:5433/app_shadow" npx knex migrate:latest

# Verify the migration is reversible
DATABASE_URL="postgres://localhost:5433/app_shadow" npx knex migrate:rollback

# Re-apply to confirm idempotency
DATABASE_URL="postgres://localhost:5433/app_shadow" npx knex migrate:latest

4. Implement rollback procedures

Create a rollback script that handles both schema and data rollbacks:

#!/bin/bash
# rollback.sh — Roll back the last N migrations
set -euo pipefail

ROLLBACK_COUNT=${1:-1}
ENVIRONMENT=${2:-staging}

echo "Rolling back $ROLLBACK_COUNT migration(s) on $ENVIRONMENT..."

# Capture current state for audit
npx knex migrate:currentVersion --env "$ENVIRONMENT" > /tmp/pre_rollback_version.txt

# Execute rollback
npx knex migrate:rollback --count "$ROLLBACK_COUNT" --env "$ENVIRONMENT"

# Verify post-rollback state
npx knex migrate:currentVersion --env "$ENVIRONMENT" > /tmp/post_rollback_version.txt

echo "Rolled back from $(cat /tmp/pre_rollback_version.txt) to $(cat /tmp/post_rollback_version.txt)"

5. CI/CD integration

Add migration checks to your pipeline:

# .github/workflows/migration-check.yml
migration-check:
  runs-on: ubuntu-latest
  services:
    postgres:
      image: postgres:16
      env:
        POSTGRES_DB: test_db
        POSTGRES_PASSWORD: test
      ports: ["5432:5432"]
  steps:
    - uses: actions/checkout@v4
    - run: npm ci
    - name: Apply all migrations from scratch
      run: npx knex migrate:latest
      env:
        DATABASE_URL: postgres://postgres:test@localhost:5432/test_db
    - name: Verify rollback works
      run: npx knex migrate:rollback --all
      env:
        DATABASE_URL: postgres://postgres:test@localhost:5432/test_db
    - name: Re-apply to confirm clean state
      run: npx knex migrate:latest
      env:
        DATABASE_URL: postgres://postgres:test@localhost:5432/test_db

Examples

Example 1: Adding a column with backfill

Prompt: "Generate a migration that adds an email_verified boolean column to the users table, defaulting to false, and backfills it to true for all users who have logged in within the last 90 days."

Agent output:

  • Creates migrations/20250217143000_add_email_verified_to_users.ts
  • The up function adds the column with a default, then runs a data backfill query using last_login_at > NOW() - INTERVAL '90 days'
  • The down function drops the column
  • Includes a note: "Backfill runs in batches of 1,000 to avoid locking the table"

Example 2: Renaming a table safely

Prompt: "I need to rename the customers table to clients without breaking the app during deployment. Generate a zero-downtime migration strategy."

Agent output:

  • Migration 1: Create clients table, add trigger to sync writes from customers to clients
  • Migration 2: Backfill existing data from customers to clients
  • Migration 3: Create a view customers pointing to clients (backwards compatibility)
  • Migration 4: Drop the view and old table after all application code references clients
  • Each migration has a working down function

Guidelines

  • Every migration must have a working down function — untested rollbacks fail when you need them most.
  • Never modify a migration that has been applied to any shared environment — create a new migration instead.
  • Use transactions for DDL when your database supports it (PostgreSQL does, MySQL does not for most DDL).
  • Test the full sequence: migrate up, roll back, migrate up again — this catches hidden state dependencies.
  • Keep migrations small — one logical change per file. A 500-line migration is a red flag.
  • Add indexes in separate migrations from table creation to avoid long locks on large tables.
  • Timestamp your migration filenames — sequential integers cause merge conflicts in teams.

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/schema-versioning-ms2s7d6c/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/schema-versioning-ms2s7d6c' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/schema-versioning-ms2s7d6c/download' --output '.skill-downloads/schema-versioning-ms2s7d6c/SKILL.md.part' && mv '.skill-downloads/schema-versioning-ms2s7d6c/SKILL.md.part' '.skill-downloads/schema-versioning-ms2s7d6c/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 : PostgreSQL 14+, MySQL 8+, or SQLite 3.35+. Node.js 18+ or Python 3.10+.

Aucune section de prérequis reconnue dans ce fichier. Cela ne signifie pas qu’il est autonome : les bibliothèques, outils et accès peuvent être cités ailleurs dans le contenu ou dans le dépôt source.

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/schema-versioning-ms2s7d6c/SKILL.md' && test -s '.skill-downloads/schema-versioning-ms2s7d6c/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/schema-versioning' && cp -R '.skill-downloads/schema-versioning-ms2s7d6c' '.claude/skills/schema-versioning'

Cursor
test -f '.skill-downloads/schema-versioning-ms2s7d6c/SKILL.md' && test -s '.skill-downloads/schema-versioning-ms2s7d6c/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/schema-versioning' && cp -R '.skill-downloads/schema-versioning-ms2s7d6c' '.cursor/skills/schema-versioning'

Codex
test -f '.skill-downloads/schema-versioning-ms2s7d6c/SKILL.md' && test -s '.skill-downloads/schema-versioning-ms2s7d6c/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/schema-versioning' && cp -R '.skill-downloads/schema-versioning-ms2s7d6c' '.agents/skills/schema-versioning'

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/schema-versioning-ms2s7d6c'

openskills read 'schema-versioning-ms2s7d6c'

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/schema-versioning-ms2s7d6c/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