Communitygithub.com

Datenbank-Migrationen

Bewährte Praktiken für Datenbank-Migrationen: Schemaänderungen, Datenmigrationen, Rollbacks und Ausfallzeit-freie Bereitstellungen für PostgreSQL, MySQL und gängige ORMs (Prisma, Drizzle, Kysely, Django, TypeORM, golang-migrate). Nutzen Sie es beim Erstellen von Schema- oder Datenmigrationen, Planen eines Rollbacks oder Anstreben einer ausfallzeitfreien Bereitstellung.

Was ist Datenbank-Migrationen?

Dieses Skill, „Datenbank-Migrationen“, bietet einen strukturierten Leitfaden für sichere, reversible Datenbankschemaänderungen in Produktionssystemen. Es behandelt Kernprinzipien wie „Jede Änderung ist eine Migration“, die Trennung von Schema- und Datenmigrationen sowie die Unveränderlichkeit bereits ausgerollter Migrationen. Das Skill enthält eine ausführliche Sicherheitscheckliste, PostgreSQL-spezifische Muster (z. B. sicheres Hinzufügen von Spalten, ausfallzeitfreies Umbenennen von Spalten mit dem Expand-Contract-Muster), Workflows und Beispiele für die sechs wichtigsten ORMs: Prisma, Drizzle, Kysely, Django, TypeORM und golang-migrate. Es werden auch Anti-Patterns wie das manuelle Ausführen von SQL in der Produktion oder das direkte Entfernen von Spalten vor dem Code hervorgehoben. Plattformunabhängig (CLI-Befehle für Kubernetes, CI/CD-Pipelines, lokale Entwicklung). Entwickler und KI-Agenten erhalten klare Anleitungen, wann das Skill aktiviert werden sollte (z. B. beim Erstellen von Tabellen, Planen von Migrationstools) und wie Migrationen sicher getestet und ausgerollt werden können.

Funktioniert mit~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/database-migrations

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

Datenbank-Migrationsmuster

Sichere, reversible Datenbankschemaänderungen für Produktionssysteme.

Wann aktivieren

  • Erstellen oder Ändern von Datenbanktabellen
  • Hinzufügen/Entfernen von Spalten oder Indizes
  • Ausführen von Datenmigrationen (Backfill, Transformation)
  • Planen von Änderungen am Schema ohne Ausfallzeit
  • Einrichten von Migrationstools für ein neues Projekt

Kernprinzipien

  1. Jede Änderung ist eine Migration – Produktionsdatenbanken niemals manuell ändern
  2. Migrationen sind in der Produktion nur vorwärts gerichtet – Rollbacks erfolgen durch neue Vorwärtsmigrationen
  3. Schema- und Datenmigrationen sind getrennt – DDL und DML niemals in einer Migration mischen
  4. Migrationen mit produktionsnahen Daten testen – eine Migration, die mit 100 Zeilen funktioniert, kann bei 10 Mio. sperren
  5. Migrationen sind nach dem Ausrollen unveränderlich – eine bereits ausgeführte Migration niemals bearbeiten

Sicherheitscheckliste für Migrationen

Vor dem Anwenden einer Migration:

  • Migration hat sowohl UP als auch DOWN (oder ist explizit als irreversibel markiert)
  • Keine vollständigen Tabellensperren bei großen Tabellen (parallele Operationen verwenden)
  • Neue Spalten haben Default-Werte oder sind nullable (niemals NOT NULL ohne Default hinzufügen)
  • Indizes gleichzeitig erstellen (nicht inline mit CREATE TABLE für bestehende Tabellen)
  • Daten-Backfill ist eine separate Migration von der Schemaänderung
  • Gegen eine Kopie der Produktionsdaten getestet
  • Rollback-Plan dokumentiert

PostgreSQL-Muster

Spalte sicher hinzufügen

-- GUT: Nullable-Spalte, keine Sperre
ALTER TABLE users ADD COLUMN avatar_url TEXT;

-- GUT: Spalte mit Default (Postgres 11+ sofort, kein Rewrite)
ALTER TABLE users ADD COLUMN is_active BOOLEAN NOT NULL DEFAULT true;

-- SCHLECHT: NOT NULL ohne Default in bestehender Tabelle (erfordert vollständigen Rewrite)
ALTER TABLE users ADD COLUMN role TEXT NOT NULL;
-- Dies sperrt die Tabelle und schreibt jede Zeile neu

Index ohne Ausfallzeit hinzufügen

-- SCHLECHT: Blockiert Schreibvorgänge bei großen Tabellen
CREATE INDEX idx_users_email ON users (email);

-- GUT: Nicht blockierend, erlaubt gleichzeitige Schreibvorgänge
CREATE INDEX CONCURRENTLY idx_users_email ON users (email);

-- Hinweis: CONCURRENTLY kann nicht innerhalb einer Transaktion ausgeführt werden
-- Die meisten Migrationstools benötigen eine spezielle Behandlung dafür

Spalte umbenennen (ohne Ausfallzeit)

Niemals direkt in der Produktion umbenennen. Das Expand-Contract-Muster verwenden:

-- Schritt 1: Neue Spalte hinzufügen (Migration 001)
ALTER TABLE users ADD COLUMN display_name TEXT;

-- Schritt 2: Daten backfillen (Migration 002, Datenmigration)
UPDATE users SET display_name = username WHERE display_name IS NULL;

-- Schritt 3: Anwendungscode aktualisieren, um beide Spalten zu lesen/schreiben
-- Anwendungsänderungen bereitstellen

-- Schritt 4: Schreiben in alte Spalte einstellen, Spalte löschen (Migration 003)
ALTER TABLE users DROP COLUMN username;

Spalte sicher entfernen

-- Schritt 1: Alle Anwendungsverweise auf die Spalte entfernen
-- Schritt 2: Anwendung ohne den Spaltenverweis bereitstellen
-- Schritt 3: Spalte in der nächsten Migration löschen
ALTER TABLE orders DROP COLUMN legacy_status;

-- Für Django: SeparateDatabaseAndState verwenden, um die Spalte aus dem Modell zu entfernen
-- ohne DROP COLUMN zu generieren (dann in der nächsten Migration löschen)

Große Datenmigrationen

-- SCHLECHT: Aktualisiert alle Zeilen in einer Transaktion (sperrt Tabelle)
UPDATE users SET normalized_email = LOWER(email);

-- GUT: Batch-Update mit Fortschritt
DO $$
DECLARE
  batch_size INT := 10000;
  rows_updated INT;
BEGIN
  LOOP
    UPDATE users
    SET normalized_email = LOWER(email)
    WHERE id IN (
      SELECT id FROM users
      WHERE normalized_email IS NULL
      LIMIT batch_size
      FOR UPDATE SKIP LOCKED
    );
    GET DIAGNOSTICS rows_updated = ROW_COUNT;
    RAISE NOTICE 'Updated % rows', rows_updated;
    EXIT WHEN rows_updated = 0;
    COMMIT;
  END LOOP;
END $$;

Prisma (TypeScript/Node.js)

Workflow

# Migration aus Schemaänderungen erstellen
npx prisma migrate dev --name add_user_avatar

# Ausstehende Migrationen in der Produktion anwenden
npx prisma migrate deploy

# Datenbank zurücksetzen (nur Entwicklung)
npx prisma migrate reset

# Client nach Schemaänderungen generieren
npx prisma generate

Schema-Beispiel

model User {
  id        String   @id @default(cuid())
  email     String   @unique
  name      String?
  avatarUrl String?  @map("avatar_url")
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @updatedAt @map("updated_at")
  orders    Order[]

  @@map("users")
  @@index([email])
}

Benutzerdefinierte SQL-Migration

Für Operationen, die Prisma nicht ausdrücken kann (gleichzeitige Indizes, Daten-Backfills):

# Leere Migration erstellen, dann SQL manuell bearbeiten
npx prisma migrate dev --create-only --name add_email_index
-- migrations/20240115_add_email_index/migration.sql
-- Prisma kann CONCURRENTLY nicht generieren, daher schreiben wir es manuell
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_email ON users (email);

Drizzle (TypeScript/Node.js)

Workflow

# Migration aus Schemaänderungen generieren
npx drizzle-kit generate

# Migrationen anwenden
npx drizzle-kit migrate

# Schema direkt pushen (nur Entwicklung, keine Migrationsdatei)
npx drizzle-kit push

Schema-Beispiel

import { pgTable, text, timestamp, uuid, boolean } from "drizzle-orm/pg-core";

export const users = pgTable("users", {
  id: uuid("id").primaryKey().defaultRandom(),
  email: text("email").notNull().unique(),
  name: text("name"),
  isActive: boolean("is_active").notNull().default(true),
  createdAt: timestamp("created_at").notNull().defaultNow(),
  updatedAt: timestamp("updated_at").notNull().defaultNow(),
});

Kysely (TypeScript/Node.js)

Workflow (kysely-ctl)

# Konfigurationsdatei initialisieren (kysely.config.ts)
kysely init

# Neue Migrationsdatei erstellen
kysely migrate make add_user_avatar

# Alle ausstehenden Migrationen anwenden
kysely migrate latest

# Letzte Migration rückgängig machen
kysely migrate down

# Migrationsstatus anzeigen
kysely migrate list

Migrationsdatei

// migrations/2024_01_15_001_create_user_profile.ts
import { type Kysely, sql } from 'kysely'

// WICHTIG: Immer Kysely<any> verwenden, nicht die typisierte DB-Schnittstelle.
// Migrationen sind zeitlich eingefroren und dürfen nicht von aktuellen Schematypen abhängen.
export async function up(db: Kysely<any>): Promise<void> {
  await db.schema
    .createTable('user_profile')
    .addColumn('id', 'serial', (col) => col.primaryKey())
    .addColumn('email', 'varchar(255)', (col) => col.notNull().unique())
    .addColumn('avatar_url', 'text')
    .addColumn('created_at', 'timestamp', (col) =>
      col.defaultTo(sql`now()`).notNull()
    )
    .execute()

  await db.schema
    .createIndex('idx_user_profile_avatar')
    .on('user_profile')
    .column('avatar_url')
    .execute()
}

export async function down(db: Kysely<any>): Promise<void> {
  await db.schema.dropTable('user_profile').execute()
}

Programmatischer Migrator

import { Migrator, FileMigrationProvider } from 'kysely'
import { promises as fs } from 'fs'
import * as path from 'path'
// Nur ESM — CJS kann __dirname direkt verwenden
import { fileURLToPath } from 'url'
const migrationFolder = path.join(
  path.dirname(fileURLToPath(import.meta.url)),
  './migrations',
)

// `db` ist Ihre Kysely<any>-Datenbankinstanz
const migrator = new Migrator({
  db,
  provider: new FileMigrationProvider({
    fs,
    path,
    migrationFolder,
  }),
  // WARNUNG: Nur in der Entwicklung aktivieren. Deaktiviert die Zeitstempel-Validierung,
  // was zu Schema-Abweichungen zwischen Umgebungen führen kann.
  // allowUnorderedMigrations: true,
})

const { error, results } = await migrator.migrateToLatest()

results?.forEach((it) => {
  if (it.status === 'Success') {
    console.log(`Migration „${it.migrationName}" erfolgreich ausgeführt`)
  } else if (it.status === 'Error') {
    console.error(`Fehler beim Ausführen der Migration „${it.migrationName}"`)
  }
})

if (error) {
  console.error('Migration fehlgeschlagen', error)
  process.exit(1)
}

Django (Python)

Workflow

# Migration aus Modelländerungen generieren
python manage.py makemigrations

# Migrationen anwenden
python manage.py migrate

# Migrationsstatus anzeigen
python manage.py showmigrations

# Leere Migration für benutzerdefiniertes SQL erstellen
python manage.py makemigrations --empty app_name -n beschreibung

Datenmigration

from django.db import migrations

def backfill_display_names(apps, schema_editor):
    User = apps.get_model("accounts", "User")
    batch_size = 5000
    users = User.objects.filter(display_name="")
    while users.exists():
        batch = list(users[:batch_size])
        for user in batch:
            user.display_name = user.username
        User.objects.bulk_update(batch, ["display_name"], batch_size=batch_size)

def reverse_backfill(apps, schema_editor):
    pass  # Datenmigration, kein Reverse nötig

class Migration(migrations.Migration):
    dependencies = [("accounts", "0015_add_display_name")]

    operations = [
        migrations.RunPython(backfill_display_names, reverse_backfill),
    ]

SeparateDatabaseAndState

Spalte aus dem Django-Modell entfernen, ohne sie sofort aus der Datenbank zu löschen:

class Migration(migrations.Migration):
    operations = [
        migrations.SeparateDatabaseAndState(
            state_operations=[
                migrations.RemoveField(model_name="user", name="legacy_field"),
            ],
            database_operations=[],  # Noch nicht in die DB eingreifen
        ),
    ]

golang-migrate (Go)

Workflow

# Migrationspaar erstellen
migrate create -ext sql -dir migrations -seq add_user_avatar

# Alle ausstehenden Migrationen anwenden
migrate -path migrations -database "$DATABASE_URL" up

# Letzte Migration rückgängig machen
migrate -path migrations -database "$DATABASE_URL" down 1

# Version erzwingen (dirty state beheben)
migrate -path migrations -database "$DATABASE_URL" force VERSION

Migrationsdateien

-- migrations/000003_add_user_avatar.up.sql
ALTER TABLE users ADD COLUMN avatar_url TEXT;
CREATE INDEX CONCURRENTLY idx_users_avatar ON users (avatar_url) WHERE avatar_url IS NOT NULL;

-- migrations/000003_add_user_avatar.down.sql
DROP INDEX IF EXISTS idx_users_avatar;
ALTER TABLE users DROP COLUMN IF EXISTS avatar_url;

Strategie für ausfallzeitfreie Migration

Bei kritischen Produktionsänderungen dem Expand-Contract-Pattern folgen:

Phase 1: EXPAND
  - Neue Spalte/Tabelle hinzufügen (nullable oder mit Default)
  - Bereitstellen: App schreibt in BEIDE, alte und neue
  - Vorhandene Daten backfillen

Phase 2: MIGRATE
  - Bereitstellen: App liest aus NEU, schreibt in BEIDE
  - Datenkonsistenz überprüfen

Phase 3: CONTRACT
  - Bereitstellen: App verwendet nur NEU
  - Alte Spalte/Tabelle in separater Migration löschen

Beispiel-Zeitplan

Tag 1: Migration fügt Spalte new_status hinzu (nullable)
Tag 1: App v2 bereitstellen — schreibt in status und new_status
Tag 2: Backfill-Migration für vorhandene Zeilen ausführen
Tag 3: App v3 bereitstellen — liest nur aus new_status
Tag 7: Migration löscht alte Spalte status

Anti-Patterns

Anti-PatternWarum es fehlschlägtBessere Vorgehensweise
Manuelles SQL in der ProduktionKein Audit-Trail, nicht wiederholbarImmer Migrationsdateien verwenden
Bereits ausgerollte Migrationen bearbeitenVerursacht Abweichungen zwischen UmgebungenStattdessen neue Migration erstellen
NOT NULL ohne DefaultSperrt Tabelle, schreibt alle Zeilen neuNullable hinzufügen, backfillen, dann Constraint hinzufügen
Inline-Index bei großer TabelleBlockiert Schreibvorgänge während der ErstellungCREATE INDEX CONCURRENTLY
Schema + Daten in einer MigrationSchwer rückgängig zu machen, lange TransaktionenGetrennte Migrationen
Spalte vor Code-Entfernung löschenAnwendungsfehler wegen fehlender SpalteCode zuerst entfernen, Spalte im nächsten Deployment löschen

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

Verwandte Skills