Elixir Language Ecto Adding a Ecto.Repo in an elixir program


This can be done in 3 steps :

  1. You must define an elixir module which use Ecto.Repo and register your app as an otp_app.

    defmodule Repo do
      use Ecto.Repo, otp_app: :custom_app
  2. You must also define some config for the Repo which will allow you to connect to the database. Here is an example with postgres.

    config :custom_app, Repo,
       adapter: Ecto.Adapters.Postgres,
       database: "ecto_custom_dev",
       username: "postgres_dev",
       password: "postgres_dev",
       hostname: "localhost",
      # OR use a URL to connect instead
      url: "postgres://postgres_dev:postgres_dev@localhost/ecto_custom_dev"
  3. Before using Ecto in your application, you need to ensure that Ecto is started before your app is started. It can be done with registering Ecto in lib/custom_app.ex as a supervisor.

        def start(_type, _args) do
          import Supervisor.Spec
          children = [
           supervisor(Repo, [])
          opts = [strategy: :one_for_one, name: MyApp.Supervisor]
          Supervisor.start_link(children, opts)