Ecto.Migration zapewnia niezalezny od bazy danych DSL do pisania i uruchamiania migracji.
Komendy CLI do migracji (CLI Migration Commands)
# Generowanie pliku migracji
mix ecto.gen.migration add_status_to_orders
# Uruchomienie oczekujacych migracji
mix ecto.migrate
# Cofniecie ostatniej migracji
mix ecto.rollback
# Sprawdzenie statusu migracji
mix ecto.migrations
DSL definicji tabeli (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
# Referencja klucza obcego
add :author_id, references(:users, on_delete: :delete_all), null: false
# Dodaje inserted_at oraz updated_at
timestamps()
end
end
end
Modyfikacja istniejących tabel (alter)
alter table(:documents) do
add :subtitle, :string
modify :title, :string, size: 255
remove :views
end
Indeksy i ograniczenia (Indices & Constraints)
# Indeks unikalny
create unique_index(:users, [:email])
# Indeks zlozony z rownoleglym tworzeniem (PostgreSQL)
create index(:orders, [:user_id, :status], concurrently: true)
# Usuniecie indeksu
drop index(:orders, [:status])
Wykonywanie surowego SQL (Raw SQL)
# Wykonywanie dowolnych komend SQL w migracji
execute "CREATE EXTENSION IF NOT EXISTS citext;"