Zum Inhalt springen
Skillpedia
Deployment & Cloud (DevOps)280k · #164

database-migrations

Was er macht

Dieser Agent hilft dir, sichere und rückgängig machbare Änderungen an der Datenbank deiner Website oder Anwendung vorzunehmen. Er sorgt dafür, dass Änderungen zurückgenommen werden können, und minimiert Ausfallzeiten bei Updates.

Wann du ihn nutzt

  • ✓Wenn Datenbanktabellen erstellt oder geändert werden.
  • ✓Wenn Spalten oder Indizes in großen Tabellen hinzugefügt oder entfernt werden.
  • ✓Wenn Updates geplant werden, die die Seite nicht offline nehmen dürfen.

Link zum Skill

https://github.com/affaan-m/ECC/blob/main/pi/core/skills/database-migrations/SKILL.md

Kopiere ihn und füge ihn in deine KI ein (Claude, ChatGPT oder Cursor) mit der Bitte, den Anweisungen zu folgen.

So nutzt du ihn

Am einfachsten: Kopiere die Nachricht und füge sie in deine KI ein. Sie liest den Skill und folgt den Anweisungen.

Fertige Nachricht zum Einfügen

Nutze diesen Skill, um mir zu helfen: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/database-migrations/SKILL.md Lies die SKILL.md unter diesem Link und folge ihren Anweisungen für meine Aufgabe.
Soll deine KI Skills wie diesen selbst finden?Installiere den kostenlosen Skillpedia-MCP: eine Zeile, und sie durchsucht vor jeder Aufgabe 15.000+ Skills.In 1 Minute installieren →

Beispielanfrage an deine KI

“Wie kann ich eine neue Spalte in eine users-Tabelle einfügen, ohne dass es zu Ausfallzeiten kommt?”

5 neue Skills pro Woche. 1 Minute Lesezeit.

So funktioniert es

Er nutzt bestimmte Muster, um die Datenbank in Etappen zu verändern. Zuerst wird die Änderung vorgenommen, dann werden bei Bedarf die Daten angepasst, und zuletzt werden alte Teile entfernt. So kann die Seite weiterlaufen.

Technischer Inhalt (originale SKILL.md)

Originaltext des Autors, auf Englisch, direkt von GitHub.

Database Migration Patterns

Safe, reversible database schema changes for production systems.

When to Activate

  • Creating or altering database tables
  • Adding/removing columns or indexes
  • Running data migrations (backfill, transform)
  • Planning zero-downtime schema changes
  • Setting up migration tooling for a new project

Core Principles

  1. Every change is a migration — never alter production databases manually
  2. Migrations are forward-only in production — rollbacks use new forward migrations
  3. Schema and data migrations are separate — never mix DDL and DML in one migration
  4. Test migrations against production-sized data — a migration that works on 100 rows may lock on 10M
  5. Migrations are immutable once deployed — never edit a migration that has run in production

Migration Safety Checklist

Before applying any migration:

  • Migration has both UP and DOWN (or is explicitly marked irreversible)
  • No full table locks on large tables (use concurrent operations)
  • New columns have defaults or are nullable (never add NOT NULL without default)
  • Indexes created concurrently (not inline with CREATE TABLE for existing tables)
  • Data backfill is a separate migration from schema change
  • Tested against a copy of production data
  • Rollback plan documented

PostgreSQL Patterns

Adding a Column Safely

-- GOOD: Nullable column, no lock
ALTER TABLE users ADD COLUMN avatar_url TEXT;

-- GOOD: Column with default (Postgres 11+ is instant, no rewrite)
ALTER TABLE users ADD COLUMN is_active BOOLEAN NOT NULL DEFAULT true;

-- BAD: NOT NULL without default on existing table (requires full rewrite)
ALTER TABLE users ADD COLUMN role TEXT NOT NULL;
-- This locks the table and rewrites every row

Adding an Index Without Downtime

-- BAD: Blocks writes on large tables
CREATE INDEX idx_users_email ON users (email);

-- GOOD: Non-blocking, allows concurrent writes
CREATE INDEX CONCURRENTLY idx_users_email ON users (email);

-- Note: CONCURRENTLY cannot run inside a transaction block
-- Most migration tools need special handling for this

Renaming a Column (Zero-Downtime)

Never rename directly in production. Use the expand-contract pattern:

-- Step 1: Add new column (migration 001)
ALTER TABLE users ADD COLUMN display_name TEXT;

-- Step 2: Backfill data (migration 002, data migration)
UPDATE users SET display_name = username WHERE display_name IS NULL;

-- Step 3: Update application code to read/write both columns
-- Deploy application changes

-- Step 4: Stop writing to old column, drop it (migration 003)
ALTER TABLE users DROP COLUMN username;

Removing a Column Safely

-- Step 1: Remove all application references to the column
-- Step 2: Deploy application without the column reference
-- Step 3: Drop column in next migration
ALTER TABLE orders DROP COLUMN legacy_status;

-- For Django: use SeparateDatabaseAndState to remove from model
-- without generating DROP COLUMN (then drop in next migration)

Large Data Migrations

-- BAD: Updates all rows in one transaction (locks table)
UPDATE users SET normalized_email = LOWER(email);

-- GOOD: Batch update with progress
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

# Create migration from schema changes
npx prisma migrate dev --name add_user_avatar

# Apply pending migrations in production
npx prisma migrate deploy

# Reset database (dev only)
npx prisma migrate reset

# Generate client after schema changes
npx prisma generate

Schema Example

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])
}

Custom SQL Migration

For operations Prisma cannot express (concurrent indexes, data backfills):


…
Häufige Fragen

Was ist eine „Migration“?

Das ist eine Reihe von Anweisungen, um die Struktur der Datenbank kontrolliert und sicher zu verändern.

Warum kann ich die Datenbank nicht einfach direkt ändern?

Direkte Änderungen können Fehler verursachen, zu Datenverlust führen oder die Seite nicht erreichbar machen. Migrationen sorgen für einen sicheren Ablauf, der sich rückgängig machen lässt.

Was bedeutet „rückgängig machbar“?

Es bedeutet, dass du bei Problemen oder wenn du eine Änderung zurücknehmen willst, einen sicheren Plan hast, um zum vorherigen Zustand zurückzukehren, ohne die Daten zu beschädigen.

Details

Originalbeschreibung des Autors

Safe, reversible database migration patterns: forward-only production changes, expand-contract zero-downtime renames, concurrent indexes, batched backfills, and per-tool workflows for PostgreSQL, Prisma, Drizzle, Kysely, Django, and golang-migrate. Use when writing a schema or data migration, adding a column or index to a large table, planning a rollback, or preparing a zero-downtime deploy.

repo: affaan-m/ECC

Beliebtheit

GitHub-Sterne
280k
Platz im Ranking
#164
Lizenz
MIT
Aktualisiert
15.10.2026

Ist dieser Skill nützlich?

0

Anmelden um abzustimmen.

Kommentare

  • …

Weitere Skills aus diesem Repository

Ähnliche Skills