Ecto for Beginners

RisingStack's services:

Search

Node.js Experts

Learn more at risingstack.com

Sign up to our newsletter!

In this article:

Ecto is a database wrapper and query generator for Elixir, so you can interact with databases in a functional and efficient way. In this guide we’ll cover the basics of Ecto, including setting up a project, defining schemas, running migrations and basic queries.

What is Ecto

Ecto is designed to work with Elixir, so it’s a flexible and robust toolset to work with databases. It supports PostgreSQL, MySQL and SQLite so it’s a good choice for any project.

Setting Up Your Ecto Project

To use Ecto you need to set up a new Elixir project and add the necessary dependencies. Here’s how:

  1. Create a New Elixir Project:

mix new my_app --module MyApp

cd my_app

  1. Add Ecto and PostgreSQL Dependencies:

In your mix.exs file add the following dependencies:

defp deps do

[

{:ecto_sql, "~> 3.6"},

{:postgrex, ">= 0.0.0"}

]

end

  1. Get the Dependencies:

mix deps.get

  1. Generate the Repo:

mix ecto.gen.repo -r MyApp.Repo

5. Configure the Repo:

    Update your config/config.exs with the database configuration:

    ```elixir

    config :my_app, MyApp.Repo,

    username: "postgres",

    password: "postgres",

    database: "my_app_dev",

    hostname: "localhost",

    show_sensitive_data_on_connection_error: true,

    pool_size: 10

    config :my_app, ecto_repos: [MyApp.Repo]

    1. Create the Database:

    mix ecto.create

    Schemas

    Schemas in Ecto are used to map database tables to Elixir structs. Here’s how you define a simple schema:

    1. Generate a Schema:

    mix ecto.gen.schema User users name:string email:string

    1. Modify the Generated Schema:

    The generated schema file will be located in lib/my_app/user.ex. It should look like this:

    defmodule MyApp.User do
    
    use Ecto.Schema
    
    import Ecto.Changeset
    
    schema "users" do
    
    field :name, :string
    
    field :email, :string
    
    timestamps()
    
    end
    
    @doc false
    
    def changeset(user, attrs) do
    
    user
    
    |> cast(attrs, [:name, :email])
    
    |> validate_required([:name, :email])
    
    end
    
    end

    Migrations

    Migrations are used to create and modify database tables. Here’s how to create and run migrations:

    1. Generate a Migration:

    mix ecto.gen.migration create_users

    1. Edit the Migration File:

    The generated migration file will be located in priv/repo/migrations/. Open it and define the changes:

    defmodule MyApp.Repo.Migrations.CreateUsers do
    use Ecto.Migration
    
    def change do
    
    create table(:users) do
    
    add :name, :string
    
     add :email, :string
    
     timestamps()
    
    end
    
    end
    
    end
    1. Run the Migration:

    mix ecto.migrate

    Ecto Queries

    Ecto provides a powerful and flexible querying syntax. Here’s how to do basic queries:

    1. Inserting Records:

    alias MyApp.{Repo, User}

    user = %User{name: "John Doe", email: "john@example.com"}

    Repo.insert!(user)

    1. Fetching Records:

    users = Repo.all(User)

    1. Updating Records:

    user = Repo.get!(User, 1)

    changeset = User.changeset(user, %{name: "Jane Doe"})

    Repo.update!(changeset)

    1. Deleting Records:

    user = Repo.get!(User, 1)

    Repo.delete!(user)

    1. Querying with Filters:

    users = Repo.all(from u in User, where: u.email == "john@example.com")

    Done

    Ecto is a must have tool for any Elixir developer working with databases. Its powerful querying capabilities, combined with Elixir’s functional nature, makes it a lot of fun to use. Now you should have a good starting point to build applications with Ecto. For more advanced features and usage, check the official Ecto documentation.

    Share this post

    Twitter
    Facebook
    LinkedIn
    Reddit

    Node.js
    Experts

    Learn more at risingstack.com

    Node.js Experts