Ecto.Migration은 데이터베이스 종류에 구애받지 않고 마이그레이션을 선언적으로 작성하고 실행할 수 있는 DSL을 제공합니다.
CLI 마이그레이션 명령어 (CLI Migration Commands)
# 신규 마이그레이션 파일 생성
mix ecto.gen.migration add_status_to_orders
# 미적용 마이그레이션 일괄 적용
mix ecto.migrate
# 가장 최근 마이그레이션 1단계 롤백
mix ecto.rollback
# 마이그레이션 적용 상태 확인
mix ecto.migrations
테이블 정의 DSL (Table Definition DSL)
defmodule MyApp.Repo.Migrations.CreateDocuments do
use Ecto.Migration
def change do
create table(:documents) do
add :title, :string, size: 100, null: false
add :body, :text
add :price, :decimal, precision: 10, scale: 2
add :views, :integer, default: 0
add :active, :boolean, default: true, null: false
add :metadata, :map # JSON / JSONB
add :published_at, :utc_datetime
# 외래 키 참조 설정
add :author_id, references(:users, on_delete: :delete_all), null: false
# inserted_at 및 updated_at 자동 추가
timestamps()
end
end
end
기존 테이블 수정 (alter)
alter table(:documents) do
add :subtitle, :string
modify :title, :string, size: 255
remove :views
end
인덱스 및 제약 조건 (Indices & Constraints)
# 고유 인덱스 (Unique Index)
create unique_index(:users, [:email])
# 복합 인덱스 (PostgreSQL 동시 생성 지원)
create index(:orders, [:user_id, :status], concurrently: true)
# 인덱스 삭제
drop index(:orders, [:status])
원시 SQL 직접 실행 (Raw SQL)
# 마이그레이션 내에서 임의의 SQL 직접 실행
execute "CREATE EXTENSION IF NOT EXISTS citext;"