🗄️ Databases

Migration

Migration

A technique for version-controlling database schema changes. Up migrations change the schema, and Down migrations roll it back. Key to team collaboration and safe deployment.

📖 Detailed Explanation

Schema migration is a method of managing the change history of a database structure (tables, columns, indexes, etc.) as code. Just as Git manages versions of source code, a migration tool manages versions of the DB schema.

Up migration is the task of changing the schema to a new version. It includes creating tables, adding columns, creating indexes, and so on. Down migration is a rollback task that reverts the changes, so you can restore the previous state when a problem occurs.

Migration file naming convention: A timestamp + description format is generally used. Example: 20240115_143022_create_users_table.sql. The timestamp guarantees the execution order, and the description tells you what the change is.

Migration table: Most tools automatically create a table (e.g., schema_migrations, flyway_schema_history) that tracks the applied migrations. This lets you check which migrations have been applied and prevents duplicate execution.

Major migration tools: These include Flyway (Java), Alembic (Python), Prisma Migrate (Node.js), Knex.js, Django Migrations, Rails Active Record Migrations, and others. Choose the tool that fits each framework and language.

💻 Code Example

# Alembic 마이그레이션 예제 - Python + SQLAlchemy

# ==============================================
# 1. alembic.ini 설정 및 초기화
# ==============================================
# pip install alembic sqlalchemy
# alembic init migrations

# migrations/env.py - 데이터베이스 연결 설정
from alembic import context
from sqlalchemy import engine_from_config, pool
from myapp.models import Base  # SQLAlchemy 모델

config = context.config
target_metadata = Base.metadata

def run_migrations_online():
    connectable = engine_from_config(
        config.get_section(config.config_ini_section),
        prefix="sqlalchemy.",
        poolclass=pool.NullPool,
    )
    with connectable.connect() as connection:
        context.configure(
            connection=connection,
            target_metadata=target_metadata
        )
        with context.begin_transaction():
            context.run_migrations()


# ==============================================
# 2. 마이그레이션 파일 생성
# ==============================================
# alembic revision -m "create users table"

# migrations/versions/20240115_create_users_table.py
"""create users table

Revision ID: a1b2c3d4e5f6
Revises:
Create Date: 2024-01-15 14:30:22.123456
"""
from alembic import op
import sqlalchemy as sa

# revision identifiers
revision = 'a1b2c3d4e5f6'
down_revision = None  # 첫 번째 마이그레이션
branch_labels = None
depends_on = None


def upgrade():
    """Up 마이그레이션 - 스키마 변경 적용"""
    op.create_table(
        'users',
        sa.Column('id', sa.Integer(), primary_key=True),
        sa.Column('email', sa.String(255), nullable=False, unique=True),
        sa.Column('username', sa.String(100), nullable=False),
        sa.Column('password_hash', sa.String(255), nullable=False),
        sa.Column('is_active', sa.Boolean(), default=True),
        sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),
        sa.Column('updated_at', sa.DateTime(), onupdate=sa.func.now()),
    )

    # 인덱스 추가
    op.create_index('ix_users_email', 'users', ['email'])
    op.create_index('ix_users_username', 'users', ['username'])


def downgrade():
    """Down 마이그레이션 - 롤백"""
    op.drop_index('ix_users_username', table_name='users')
    op.drop_index('ix_users_email', table_name='users')
    op.drop_table('users')


# ==============================================
# 3. 두 번째 마이그레이션 - 컬럼 추가
# ==============================================
# alembic revision -m "add profile columns to users"

"""add profile columns to users

Revision ID: b2c3d4e5f6g7
Revises: a1b2c3d4e5f6
"""
revision = 'b2c3d4e5f6g7'
down_revision = 'a1b2c3d4e5f6'


def upgrade():
    # 컬럼 추가 (nullable=True로 시작)
    op.add_column('users', sa.Column('avatar_url', sa.String(500), nullable=True))
    op.add_column('users', sa.Column('bio', sa.Text(), nullable=True))

    # 새 테이블 추가
    op.create_table(
        'user_profiles',
        sa.Column('id', sa.Integer(), primary_key=True),
        sa.Column('user_id', sa.Integer(), sa.ForeignKey('users.id'), unique=True),
        sa.Column('phone', sa.String(20)),
        sa.Column('address', sa.Text()),
    )


def downgrade():
    op.drop_table('user_profiles')
    op.drop_column('users', 'bio')
    op.drop_column('users', 'avatar_url')


# ==============================================
# 4. 마이그레이션 실행 명령어
# ==============================================
# 최신 버전으로 업그레이드
# alembic upgrade head

# 특정 버전으로 업그레이드
# alembic upgrade a1b2c3d4e5f6

# 한 단계 롤백
# alembic downgrade -1

# 특정 버전으로 롤백
# alembic downgrade a1b2c3d4e5f6

# 현재 버전 확인
# alembic current

# 마이그레이션 히스토리 확인
# alembic history
// Prisma 마이그레이션 예제 - Node.js / TypeScript

// ==============================================
// 1. Prisma 스키마 정의 (prisma/schema.prisma)
// ==============================================

/*
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model User {
  id          Int       @id @default(autoincrement())
  email       String    @unique
  username    String
  passwordHash String   @map("password_hash")
  isActive    Boolean   @default(true) @map("is_active")
  createdAt   DateTime  @default(now()) @map("created_at")
  updatedAt   DateTime  @updatedAt @map("updated_at")

  // 관계
  posts       Post[]
  profile     Profile?

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

model Profile {
  id        Int     @id @default(autoincrement())
  userId    Int     @unique @map("user_id")
  phone     String?
  address   String?
  avatarUrl String? @map("avatar_url")
  bio       String?

  user      User    @relation(fields: [userId], references: [id])

  @@map("user_profiles")
}

model Post {
  id        Int      @id @default(autoincrement())
  title     String
  content   String?
  published Boolean  @default(false)
  authorId  Int      @map("author_id")
  createdAt DateTime @default(now()) @map("created_at")

  author    User     @relation(fields: [authorId], references: [id])

  @@map("posts")
  @@index([authorId])
}
*/


// ==============================================
// 2. 마이그레이션 명령어
// ==============================================

// 마이그레이션 생성 및 적용
// npx prisma migrate dev --name init

// 프로덕션에 마이그레이션 적용
// npx prisma migrate deploy

// 마이그레이션 상태 확인
// npx prisma migrate status

// 스키마 리셋 (개발 환경만!)
// npx prisma migrate reset


// ==============================================
// 3. 생성된 마이그레이션 파일 예시
// ==============================================

// prisma/migrations/20240115143022_init/migration.sql
/*
-- CreateTable
CREATE TABLE "users" (
    "id" SERIAL NOT NULL,
    "email" TEXT NOT NULL,
    "username" TEXT NOT NULL,
    "password_hash" TEXT NOT NULL,
    "is_active" BOOLEAN NOT NULL DEFAULT true,
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updated_at" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "users_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "user_profiles" (
    "id" SERIAL NOT NULL,
    "user_id" INTEGER NOT NULL,
    "phone" TEXT,
    "address" TEXT,
    "avatar_url" TEXT,
    "bio" TEXT,

    CONSTRAINT "user_profiles_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "users_email_key" ON "users"("email");
CREATE INDEX "users_email_idx" ON "users"("email");
CREATE INDEX "users_username_idx" ON "users"("username");

-- CreateIndex
CREATE UNIQUE INDEX "user_profiles_user_id_key" ON "user_profiles"("user_id");

-- AddForeignKey
ALTER TABLE "user_profiles" ADD CONSTRAINT "user_profiles_user_id_fkey"
    FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
*/


// ==============================================
// 4. 프로그래밍 방식 마이그레이션 (Knex.js)
// ==============================================

// knexfile.js
module.exports = {
    development: {
        client: 'postgresql',
        connection: process.env.DATABASE_URL,
        migrations: {
            directory: './migrations',
            tableName: 'knex_migrations'
        }
    }
};

// migrations/20240115143022_create_users.js
exports.up = function(knex) {
    return knex.schema
        .createTable('users', (table) => {
            table.increments('id').primary();
            table.string('email', 255).notNullable().unique();
            table.string('username', 100).notNullable();
            table.string('password_hash', 255).notNullable();
            table.boolean('is_active').defaultTo(true);
            table.timestamps(true, true);  // created_at, updated_at

            table.index('email');
            table.index('username');
        })
        .createTable('user_profiles', (table) => {
            table.increments('id').primary();
            table.integer('user_id').unsigned().unique()
                .references('id').inTable('users');
            table.string('phone', 20);
            table.text('address');
        });
};

exports.down = function(knex) {
    return knex.schema
        .dropTableIfExists('user_profiles')
        .dropTableIfExists('users');
};

// 실행: npx knex migrate:latest
// 롤백: npx knex migrate:rollback
-- ============================================
-- Flyway 마이그레이션 예제 (Raw SQL)
-- ============================================

-- 파일명: V1__create_users_table.sql
-- V{버전}__{설명}.sql 형식 (언더스코어 2개)

CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    email VARCHAR(255) NOT NULL UNIQUE,
    username VARCHAR(100) NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX ix_users_email ON users(email);
CREATE INDEX ix_users_username ON users(username);

-- 트리거: updated_at 자동 갱신
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = CURRENT_TIMESTAMP;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER update_users_updated_at
    BEFORE UPDATE ON users
    FOR EACH ROW
    EXECUTE FUNCTION update_updated_at_column();


-- ============================================
-- 파일명: V2__add_user_profiles.sql
-- ============================================

CREATE TABLE user_profiles (
    id SERIAL PRIMARY KEY,
    user_id INTEGER UNIQUE REFERENCES users(id) ON DELETE CASCADE,
    phone VARCHAR(20),
    address TEXT,
    avatar_url VARCHAR(500),
    bio TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- users 테이블에 컬럼 추가
ALTER TABLE users ADD COLUMN last_login_at TIMESTAMP;
ALTER TABLE users ADD COLUMN login_count INTEGER DEFAULT 0;


-- ============================================
-- 파일명: V3__create_posts_table.sql
-- ============================================

CREATE TABLE posts (
    id SERIAL PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    content TEXT,
    slug VARCHAR(255) UNIQUE,
    published BOOLEAN DEFAULT FALSE,
    author_id INTEGER NOT NULL REFERENCES users(id),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    published_at TIMESTAMP
);

CREATE INDEX ix_posts_author ON posts(author_id);
CREATE INDEX ix_posts_published ON posts(published) WHERE published = TRUE;
CREATE INDEX ix_posts_slug ON posts(slug);


-- ============================================
-- 무중단 마이그레이션 패턴 (대용량 테이블)
-- ============================================

-- V4__add_status_column_safe.sql
-- 1단계: nullable 컬럼 추가 (락 최소화)
ALTER TABLE posts ADD COLUMN status VARCHAR(20);

-- V5__backfill_status_column.sql
-- 2단계: 기존 데이터 백필 (배치로 처리)
UPDATE posts SET status = 'published' WHERE published = TRUE AND status IS NULL;
UPDATE posts SET status = 'draft' WHERE published = FALSE AND status IS NULL;

-- V6__add_status_constraints.sql
-- 3단계: NOT NULL 및 제약 조건 추가
ALTER TABLE posts ALTER COLUMN status SET DEFAULT 'draft';
ALTER TABLE posts ALTER COLUMN status SET NOT NULL;
ALTER TABLE posts ADD CONSTRAINT chk_posts_status
    CHECK (status IN ('draft', 'published', 'archived'));


-- ============================================
-- Flyway 명령어
-- ============================================

-- 마이그레이션 적용
-- flyway -url=jdbc:postgresql://localhost/mydb -user=postgres migrate

-- 현재 상태 확인
-- flyway info

-- 마이그레이션 검증
-- flyway validate

-- 히스토리 정리 (주의!)
-- flyway repair

🗣️ Say It Like This in Practice

💬 In a pre-deployment code review
"This PR includes a migration file, but have you tested the down migration too? If a problem occurs after the production deployment, we'll have to roll back, so let's verify in staging that down works properly before we go ahead."
💬 When changing the schema of a large table
"The users table has 100 million rows, so adding NOT NULL with ALTER TABLE will lock it. Let's split it into 3 steps. First add the column as nullable, then backfill in the background, and finally add the constraint."
💬 When onboarding a new team member
"Setting up the local DB is simple. Set DATABASE_URL in .env and run 'prisma migrate dev' once, and you're done. Because the migration history is in Git, the whole team can keep the same schema."

⚠️ Cautions & Best Practices

❌
Do not modify applied migrations

Modifying a migration that has already been applied to other environments causes an error due to a checksum mismatch. If a change is needed, create a new migration.

❌
Missing down migration

A migration that cannot be rolled back makes incident response difficult. Always write and test the down migration.

❌
Running ALTER directly on a large table

Running ALTER TABLE directly on a table with hundreds of millions of rows causes a long lock. Use zero-downtime tools such as pt-online-schema-change or gh-ost.

✅
Migration best practices

Split migrations into small pieces, version them together with Git, run them automatically in CI/CD, apply to staging first and then production, and handle data migrations with separate scripts.

🔗 Related Terms

📚 Learn More