LogoSkills

/cc-serverpod:merge-migrations — 흩어진 DB 변경 기록을 하나로 합치기

여러 migration을 하나로 병합합니다 (프로덕션 배포 전 정리)

/cc-serverpod:merge-migrations — 흩어진 DB 변경 기록을 하나로 합치기#

항목내용
실행 명령/cc-serverpod:merge-migrations
분류Serverpod
난이도●●○ 보통

한마디로#

개발하면서 조금씩 쌓인 여러 개의 "DB 변경 기록(마이그레이션)"을 하나로 깔끔하게 묶어주는 정리 도구입니다. 여러 장으로 찢어진 영수증을 한 장으로 정리해 두는 것과 같아요. 운영(실서비스) 서버에는 손대지 않고, 개발 환경에서만 정리합니다.

누가·언제 쓰나요#

  • 개발 중에 DB 구조 변경 기록이 여러 개로 잘게 쌓여서, 실서비스 배포 전에 깔끔하게 정리하고 싶을 때
  • 마이그레이션 히스토리(변경 이력)가 지저분해서 보기 좋게 합치고 싶을 때

👉 백엔드(Serverpod) 개발자가 주로 사용하며, 이미 운영 서버에 반영된 기록은 건드리지 않고 그 이후에 생긴 개발용 기록들만 합칩니다.

무엇을 해주나요#

여러 개로 나뉜 마이그레이션을 하나의 새 마이그레이션으로 합쳐줍니다. 구체적으로:

  • 합치기 전에 기존 마이그레이션을 migrations_backup/ 폴더에 자동 백업
  • 새로 합쳐진 마이그레이션 폴더 1개 생성 (그 안에 definition.sql, migration.sql 등 실제 파일들)
  • 변경 이력 목록 파일인 migration_registry.txt 자동 갱신
  • 운영 서버에 이미 반영된 기준 마이그레이션(--base)은 그대로 보존

어떻게 쓰나요#

# 기본: 기준(--base) 이후에 생긴 모든 마이그레이션을 자동으로 찾아 합치기
/cc-serverpod:merge-migrations --base 20251223123500000

# 합칠 범위를 직접 지정 (시작~)
/cc-serverpod:merge-migrations \
  --base 20251223123500000 \
  --from 20251229134213396 \
  --to 20260113023207235

# 미리보기만 (실제로 바꾸지 않고 결과만 확인)
/cc-serverpod:merge-migrations --base 20251223123500000 --dry-run
  • --base (필수): 운영 서버에 이미 적용된 기준 마이그레이션 ID. 이 ID는 절대 건드리지 않으며, 이 시점 이후의 개발용 기록만 정리 대상이 됩니다.
  • --from / --to: 합칠 시작·끝 지점. 비워두면 자동으로 잡아줍니다.
  • --name: 합쳐진 마이그레이션에 붙일 이름.
  • --dry-run: 실제 변경 없이 미리보기만 합니다.

안에서 무슨 일이 벌어지나요#

  1. 분석 — 기준(--base) 이후에 생긴 마이그레이션들을 모아, 어떤 테이블이 바뀌는지 표로 보여줍니다.
  2. 합치기 미리보기 — 흩어진 변경 내용(SQL)을 하나로 합쳤을 때 어떻게 되는지 미리 보여줍니다.
  3. 사용자 확인 — "기존 파일이 삭제되고 로컬에서만 실행된다"는 주의사항을 안내하고, 진행할지(Y/n) 물어봅니다.
  4. 실행 — 기존 마이그레이션을 백업한 뒤 삭제하고, 합쳐진 새 마이그레이션을 만들고, 이력 목록을 갱신합니다.
  5. 검증 — 합치기 완료 결과와 백업 위치, 다음에 할 일(로컬 DB 재설정·커밋)을 알려줍니다.

운영 서버는 영향을 받지 않습니다. 운영 DB는 이미 적용된 기록을 따로 관리(serverpod_migrations 테이블)하기 때문이며, 합쳐진 마이그레이션은 새 환경에서만 쓰입니다. 다른 팀원과 동시에 작업하면 충돌이 생길 수 있으니, 합치기 전에 팀원과 조율하는 것이 좋습니다.


⚙️ 상세 옵션·실행 명세 (개발자 / AI 에이전트용)

Triggers#

  • When cleaning up migrations before production deployment
  • When consolidating multiple development migrations into one
  • When cleaning up migration history

Context Trigger Pattern#

/cc-serverpod:merge-migrations --base {production_migration} [--options]

Parameters#

ParameterRequiredDescriptionExample
--baseProduction baseline migration ID (this ID is preserved)20251223123500000
--fromMerge start migration (auto-detected after base if not specified)20251229134213396
--toMerge end migration (auto-detected as latest if not specified)20260113023207235
--nameMerged migration nameconsolidated_dev
--dry-runPreview only without actual changestrue/false

Note: --base is always required. Specify the production-applied migration ID to only merge development migrations after that point.

Behavioral Flow#

Step 1: Migration Analysis#

## Migration Analysis

**Production baseline**: {base_migration}
**Merge targets**: {count}

| # | Migration ID | Created | Changed Tables |
|---|-------------|---------|----------------|
| 1 | 20251229134213396 | 2025-12-29 | coupon |
| 2 | 20260112140301453 | 2026-01-12 | author |
| 3 | 20260113023207235 | 2026-01-13 | author |

**Affected tables**: coupon, author

Step 2: SQL Merge#

## SQL Merge Preview

### Before merge (individual migrations)
sql

-- Migration 1: 20251229134213396 ALTER TABLE "coupon" ADD COLUMN "new_field" text;

-- Migration 2: 20260112140301453 ALTER TABLE "author" ADD COLUMN "memo" text;

-- Migration 3: 20260113023207235 ALTER TABLE "author" ADD COLUMN "extra" text;


 ### After merge (single migration)
sql

-- Migration: {new_migration_id} BEGIN;

ALTER TABLE "coupon" ADD COLUMN "new_field" text; ALTER TABLE "author" ADD COLUMN "memo" text; ALTER TABLE "author" ADD COLUMN "extra" text;

-- MIGRATION VERSION FOR kobic INSERT INTO "serverpod_migrations" ("module", "version", "timestamp") VALUES ('kobic', '{new_migration_id}', now()) ON CONFLICT ("module") DO UPDATE SET "version" = '{new_migration_id}', "timestamp" = now();

COMMIT;

Step 3: User Confirmation#

## Merge Confirmation

**Caution**:
- This operation deletes existing migration files
- Run only on local development DB
- Existing migrations must already be applied to the production DB

**Proceed with merge? (Y/n)**

Step 4: Execute Merge#

# 1. Backup existing migrations
mkdir -p migrations_backup
for dir in migrations/{from} migrations/{middle} migrations/{to}; do
  cp -r  " $dir "   migrations_backup/
done

# 2. Delete existing migrations
rm -rf migrations/{from}
rm -rf migrations/{middle}
rm -rf migrations/{to}

# 3. Create new migration
serverpod create-migration --experimental-features=all

# 4. Update migration_registry.txt
# Remove old migration IDs, add new ID

Step 5: Verification#

## Merge Complete

Existing migrations backed up: `migrations_backup/`
New migration created: `{new_migration_id}`
migration_registry.txt updated

### Next Steps

1. **Reset local DB** (optional):
   
bash

Recreate local DB from scratch#

melos run backend:pod:run-migration


 2. **Commit changes**:
   
bash

git add backend/kobic_server/migrations/ git commit -m "chore(migration): merge migrations ({from}~{to} → {new_id})"


 ### Backup Location
Existing migrations are stored in `migrations_backup/`

Output Files#

backend/kobic_server/
├── migrations/
│   ├── {base_migration}/           # Production (preserved)
│   ├── {new_migration}/            # Newly created merged migration
│   │   ├── definition.json
│   │   ├── definition.sql
│   │   ├── definition_project.json
│   │   ├── migration.json
│   │   └── migration.sql
│   └── migration_registry.txt      # Updated
├── migrations_backup/              # Backup (can be deleted)
│   ├── {old_migration_1}/
│   ├── {old_migration_2}/
│   └── ...

Manual Merge Guide (Instead of Script)#

If the skill does not auto-execute, follow these steps manually:

1. Check Current State#

# Check migration_registry.txt
cat backend/kobic_server/migrations/migration_registry.txt

# Check post-production migrations
ls -la backend/kobic_server/migrations/ | grep  " 2026 "

2. Backup and Delete Existing Migrations#

cd backend/kobic_server

# Backup
mkdir -p migrations_backup
mv migrations/20251229134213396 migrations_backup/
mv migrations/20260112140301453 migrations_backup/
mv migrations/20260113023207235 migrations_backup/

# Remove the corresponding lines from migration_registry.txt
# Manually edit to remove the migration IDs to be deleted

3. Create New Migration#

# Code generation (based on current models)
melos run backend:pod:generate

# Create new migration
melos run backend:pod:create-migration

4. Verify#

# Check new migration
ls -la backend/kobic_server/migrations/ | tail -5

# Check migration_registry.txt
tail backend/kobic_server/migrations/migration_registry.txt

Examples#

Basic usage (production baseline)#

Auto-detect and merge all migrations after --base:

/cc-serverpod:merge-migrations --base 20251223123500000

Range specification#

Merge specific range based on --base (after base ~ to):

/cc-serverpod:merge-migrations \
  --base 20251223123500000 \
  --from 20251229134213396 \
  --to 20260113023207235

Dry-run (preview)#

Preview merged content without actual changes:

/cc-serverpod:merge-migrations --base 20251223123500000 --dry-run

Core Rules#

  1. Production baseline: Do not touch production-applied migrations
  2. Backup required: Always backup before deletion
  3. Local only: Never run on production DB
  4. Order preserved: Migration order is automatically managed by timestamp
  5. Verification required: Verify with melos run backend:pod:generate after merge

Cautions#

Production DB caution:

  • Existing migrations are already applied to the production DB
  • Merged migrations are only used in new environments
  • Existing production is unaffected (references serverpod_migrations table)

Team collaboration:

  • Migration conflicts possible with other developers
  • Coordinate with team members before merging
  • Check migration_registry.txt conflicts before PR merge