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
  ]
end

Install dependencies:

mix deps.get

πŸ”§ Step 3: Generate Ecto Repository

mix ecto.gen.repo -r MyApp.Repo

This 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_users

Edit 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
end

Run 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