Initial Setup
Get Elixir Ecto installed and create your first database migration. This guide walks you through setting up Ecto for database operations in Elixir.
π― What You’ll Accomplish
By the end of this tutorial, you’ll have:
- β Elixir and Ecto installed
- β Database connection configured
- β Your first migration created and run
- β Basic database operations working
π Prerequisites
- Elixir 1.14 or later installed
- PostgreSQL or MySQL installed
- Basic familiarity with Elixir syntax
πΎ Step 1: Create New Elixir Project
mix new myapp
cd myappπ¦ Step 2: Add Ecto Dependencies
Edit mix.exs:
defp deps do
[
{:ecto_sql, "~> 3.11"},
{:postgrex, "~> 0.17"} # For PostgreSQL
# {:myxql, "~> 0.6"} # For MySQL
]
endInstall dependencies:
mix deps.getπ§ Step 3: Generate Ecto Repository
mix ecto.gen.repo -r MyApp.RepoThis creates lib/myapp/repo.ex.
βοΈ Step 4: Configure Database
Edit config/config.exs:
config :myapp, MyApp.Repo,
database: "myapp_dev",
username: "postgres",
password: "postgres",
hostname: "localhost"
config :myapp, ecto_repos: [MyApp.Repo]ποΈ Step 5: Create Database
mix ecto.createπ Step 6: Create Your First Migration
mix ecto.gen.migration create_usersEdit the generated migration file:
defmodule MyApp.Repo.Migrations.CreateUsers do
use Ecto.Migration
def change do
create table(:users) do
add :name, :string, null: false
add :email, :string, null: false
add :age, :integer
timestamps()
end
create unique_index(:users, [:email])
end
endRun the migration:
mix ecto.migrateβ Verification Checklist
Before moving forward, verify:
- Elixir and Ecto dependencies installed
- Database connection configured
- Database created with
mix ecto.create - Migration created and run successfully
π You’re Done!
You’ve successfully set up Ecto and created your first migration. You’re ready to work with database operations.
π What’s Next?
Quick learner: Elixir Ecto Quick Start
Code-first learner: Elixir Ecto By Example
Last updated