クイックリファレンス

Phoenix Ecto マイグレーション チートシート

PhoenixにおけるEctoデータベースマイグレーションのクイックリファレンス:テーブル作成、カラム型、外部キー制約、複合インデックス、生SQL実行。

· 公開日

Ecto.Migration は、PhoenixおよびElixirアプリケーションでデータベースマイグレーションを記述・実行するための抽象化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)

# ユニーク制約インデックス
create unique_index(:users, [:email])

# 複合インデックス(PostgreSQL並行作成指定)
create index(:orders, [:user_id, :status], concurrently: true)

# インデックスの削除
drop index(:orders, [:status])

生SQLの実行(Raw SQL Execution)

# マイグレーション内で任意のSQL文を直接実行
execute "CREATE EXTENSION IF NOT EXISTS citext;"

関連リファレンス

関連テーマ