Files
portfolio-hub/docs/batches/bat-001_20260519_asset-catalog-db-foundation/planning.md
T
genichin e2226e28b6 feat: implement asset catalog database foundation (BAT-001, REQ-009/011/014)
Asset Catalog Model Implementation (BAT-001):
- Introduce assets table with UUID PK, symbol UNIQUE, markets TEXT[] array
- Define MarketCode enum (KRX, NXT, SOR, NASDAQ, NYSE, UPBIT, BITHUMB)
- Add Asset domain model with catalog properties
- Implement asset CRUD protocols in portfolio_repository
- Add PostgreSQL asset CRUD operations with GIN index on markets

Portfolio Model Refactoring (REQ-011):
- Add portfolios.asset_id UUID FK to assets(asset_id) ON DELETE RESTRICT
- Remove portfolios.symbol and portfolios.market columns
- Update Portfolio domain model to reference asset_id instead of symbol/market
- Refactor all portfolio queries to JOIN assets catalog
- Update all repository methods to use asset references

Data Migration (REQ-014):
- Create 20260519_0017 Alembic revision for assets table creation
- Create 20260519_0018 Alembic revision for atomic data migration:
  * Extract unique symbol combinations from portfolios
  * Aggregate markets using ARRAY_AGG(DISTINCT market)
  * Populate assets catalog with extracted data
  * Update portfolios.asset_id to reference new assets
  * Remove legacy symbol/market columns in single transaction
- Implement migration with rollback support

Requirements Approved (REQ-001~008):
- REQ-001~008 transitioned from Proposed to Approved
- Complete tag model requirement set with implementation readiness

New Requirements Approved (REQ-009~015):
- REQ-009: assets table schema (approved, included in BAT-001)
- REQ-010: admin asset catalog CRUD (approved, future BAT-002)
- REQ-011: portfolios asset_id FK (approved, included in BAT-001)
- REQ-012: portfolio create catalog validation (approved, future BAT-002)
- REQ-013: GET /v1/assets token branching (approved, future BAT-002)
- REQ-014: portfolios data migration (approved, included in BAT-001)
- REQ-015: asset catalog baseline docs (approved)

Code Changes:
- app/domain/models.py: Add Asset model, MarketCode enum, Portfolio asset_id FK
- app/repositories/portfolio_repository.py: Define asset CRUD protocol
- app/repositories/postgres.py: Implement asset operations with full CRUD
- app/api/v1_assets.py: Remove symbol/market direct references
- app/cli/commands/portfolio.py: Update portfolio commands for asset references
- app/schemas/portfolio.py: Update portfolio schema with asset_id
- All portfolio operations throughout codebase: Use asset references

Testing:
- Add test_asset_catalog.py for asset CRUD operations
- Verify REQ-009 AC-1~5 (asset catalog creation, lookup, uniqueness)
- Verify REQ-011 AC-1~5 (FK constraint, portfolio asset reference)
- Verify REQ-014 AC-1~6 (migration atomicity, data correctness, rollback)
- Update existing tests for asset model usage

Documentation:
- Create BAT-001 batch documents (planning, design, implementation, verification)
- Update dcy-001 with implementation details and confirmed architecture
- Add 8 new requirement documents (REQ-009~015)
- Update docs/discovery/index.md with batch entry

Impact:
- Database: assets catalog table, portfolios refactored to reference assets
- Migration: 2 new Alembic revisions (0017 assets, 0018 portfolio migration)
- API: Symbol/market now accessed through asset references
- CLI: Portfolio commands require asset reference pattern
- All existing portfolio data preserved and correctly migrated
2026-05-19 15:59:20 +00:00

4.3 KiB

BAT-001 Planning

  • Status: verified
  • Batch: BAT-001
  • Profile: standard

Included REQ

  • REQ-009: assets 테이블 스키마 도입 (Data, High)
  • REQ-011: portfolios 테이블 asset_id FK 추가 및 symbol/market 제거 (Data, High)
  • REQ-014: portfolios 데이터 migration (Migration, High)

Delivery Plan

단계 1 — REQ-009: assets 테이블 및 도메인 레이어

  1. app/domain/models.py에 MarketCode Enum(KRX, NXT, SOR, NASDAQ, NYSE, UPBIT, BITTHUMB) 추가
  2. app/domain/models.py에 Asset 도메인 모델(asset_id, symbol, markets, display_name, status, created_at, updated_at) 추가
  3. app/repositories/portfolio_repository.py Protocol에 asset CRUD 메서드 선언(get_asset_by_id, get_asset_by_symbol, list_assets, insert_asset, update_asset)
  4. app/repositories/postgres.py에 asset CRUD SQL 구현 추가
  5. Alembic revision (rev-A): assets 테이블 생성 + idx_assets_markets_gin GIN 인덱스 생성
  6. tests/test_asset_catalog.py 신규 — REQ-009 AC-1~5 테스트

단계 2 — REQ-011 + REQ-014: portfolios 재설계 + 데이터 이전 (결합 revision)

  1. 구현 전 grep -rn "\.symbol\|\.market" app/ 실행 — 수정 대상 모듈 전수 파악 (R-2)
  2. Alembic revision (rev-B): 아래를 단일 트랜잭션으로 처리
    • 사전 검증 쿼리: SELECT symbol, ARRAY_AGG(DISTINCT market) FROM portfolios GROUP BY symbol 실행
    • assets catalog에 기존 portfolios 데이터 이전 (symbol 기준 DISTINCT, ARRAY_AGG(DISTINCT market))
    • portfolios.asset_id UUID NOT NULL 컬럼 추가 + FK REFERENCES assets(asset_id) ON DELETE RESTRICT
    • 각 portfolio 행에 asset_id 채우기
    • portfolios.symbol, portfolios.market 컬럼 제거
  3. app/domain/models.py의 Portfolio 모델 — symbol/market 제거, asset_id 추가
  4. app/repositories/postgres.py — portfolios 쿼리를 assets JOIN portfolios 형태로 변경
  5. symbol/market 직접 참조 모듈 수정:
    • app/api/portfolios.py
    • app/api/v1_assets.py
    • app/cli/commands/portfolio.py
    • app/schemas/ (PortfolioListItem 등)
  6. tests/test_asset_catalog.py — REQ-011 AC-15, REQ-014 AC-16 추가

단계 3 — 전체 테스트 suite 회귀 검증

  • 기존 테스트 suite 실행 — symbol/market 참조 갱신 후 regression 없음 확인

Dependencies

  • Internal:
    • rev-A(REQ-009 assets 테이블)가 rev-B(REQ-011+014 portfolios 변경) 선행 조건 — 같은 batch 내 순서 보장
    • REQ-011 schema 변경과 REQ-014 데이터 이전은 동일 Alembic revision(rev-B)으로 결합하거나 rev-B-1(데이터 이전) → rev-B-2(symbol/market DROP) 순서로 분리 — design 단계에서 결정
  • External:
    • 없음 (로컬 Postgres, 기존 인프라 변경 없음)

Design Gate

  • Design Required Before Implementation: yes
  • Reason: (1) Alembic revision 분리 전략(단일 revision vs 2-step) 결정 필요 — 운영 데이터 롤백 안전성 영향; (2) rev-B에서 portfolios.asset_id NOT NULL 추가 시 NULL 허용 단계 없이 바로 NOT NULL 가능한지 마이그레이션 순서 검증 필요; (3) symbol/market 참조 grep 결과에 따라 수정 범위가 변동될 수 있음

Milestones

  1. REQ-009: assets 테이블 Alembic revision + domain model + repository layer 완성 + AC-1~5 통과
  2. REQ-011 + REQ-014: portfolios 재설계 Alembic revision(rev-B) + 도메인 코드 전수 수정 완성 + AC-1~6 통과
  3. 기존 테스트 suite 전체 regression 통과

Risks

  • R-2(High): grep -rn "\.symbol\|\.market" app/ 결과 범위 예측 불가 — 수정 누락 시 런타임 AttributeError 발생. 대응: 구현 착수 전 grep 결과를 planning에 기록 후 수정 체크리스트 작성
  • R-1(High): 동일 symbol 여러 포트폴리오 행의 market 값 충돌 — ARRAY_AGG(DISTINCT market) 집약 규칙으로 처리. 대응: migration dry-run 후 asset 수 = DISTINCT symbol 수 일치 확인 (REQ-014 AC-2)
  • R-3(Medium): portfolios.asset_id NOT NULL 추가 시 기존 행에 NULL 발생 — 데이터 이전이 완료된 후에 NOT NULL 제약 적용 순서 보장 필요. 대응: revision 내 순서 검증 (데이터 먼저, NOT NULL 제약 나중)
  • R-4(Low): rev-B 단일 트랜잭션에서 대용량 portfolios 테이블 lock — 로컬 테스트 환경에서는 무시 가능; 운영 환경 고려 시 design 단계에서 검토