Ecto.Migration bietet eine datenbankunabhaengige DSL zum Schreiben und Ausfuehren von Migrationen in Phoenix und Elixir.
CLI-Migrationsbefehle (CLI Migration Commands)
# Neue Migrationsdatei generieren
mix ecto.gen.migration add_status_to_orders
# Ausstehende Migrationen ausfuehren
mix ecto.migrate
# Letzten Migrationsschritt zuruecksetzen
mix ecto.rollback
# Migrationsstatus pruefen
mix ecto.migrations
Tabellendefinitions-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
# Fremdschluessel-Referenz
add :author_id, references(:users, on_delete: :delete_all), null: false
# Fuegt inserted_at und updated_at hinzu
timestamps()
end
end
end
Bestehende Tabellen aendern (alter)
alter table(:documents) do
add :subtitle, :string
modify :title, :string, size: 255
remove :views
end
Indizes und Constraints (Indices & Constraints)
# Eindeutiger Index
create unique_index(:users, [:email])
# Zusammengesetzter Index mit nebenlaeufiger Erstellung (PostgreSQL)
create index(:orders, [:user_id, :status], concurrently: true)
# Index entfernen
drop index(:orders, [:status])
Ausfuehrung von Roh-SQL (Raw SQL)
# Benutzerdefinierte SQL-Befehle in der Migration ausfuehren
execute "CREATE EXTENSION IF NOT EXISTS citext;"