How do I create a custom Repo and coresponding migrations?

The custom repo is added in dev.exs, config.exs, and application.ex as such

config :nsMetrics, MyApp.CustomRepo,
  username: "postgres",
  password: "postgres",
  database: "table_name",
  hostname: "localhost",
  pool_size: 10
config :myApp,
  ecto_repos: [
MyApp.CustomRepo
]
 def start(_type, _args) do
    children = [
MyApp.CustomRepo
]

Errors:

terminal:path$ mix ecto.gen.migration table_name -r MpApp.CustomRepo
** (Mix) Could not load MyApp.CustomRepo, error: :nofile. Please configure your app accordingly or pass a repo with the -r option.

terminal:path$ mix ecto.create -r MpApp.CustomRepo
** (Mix) Could not load MpApp.CustomRepo, error: :nofile. Please configure your app accordingly or pass a repo with the -r option.

If I run mix phx.gen.schema MpApp.CustomRepo table_name field_1:string field_2:map followed by mix ecto.migrate it will create the migration but it inserts the table under MyApp.Repo and returns

** (Mix) Could not load MpApp.CustomRepo, error: :nofile. Please configure your app accordingly or pass a repo with the -r option.
** (exit) 1
    (mix 1.13.4) lib/mix/tasks/cmd.ex:64: Mix.Tasks.Cmd.run/1
    init.exs:18: Mix.Tasks.Ns.Init.run/1
    (mix 1.13.4) lib/mix/task.ex:397: anonymous fn/3 in Mix.Task.run_task/3
    (mix 1.13.4) lib/mix/cli.ex:84: Mix.CLI.run_task/2
** (exit) 1
    (mix 1.13.4) lib/mix/tasks/cmd.ex:64: Mix.Tasks.Cmd.run/1
    (elixir 1.13.4) lib/enum.ex:1593: Enum."-map/2-lists^map/1-0-"/2
    server.exs:81: Mix.Tasks.Ns.Server.parse_args/1
    server.exs:61: Mix.Tasks.Ns.Server.run/1
    (mix 1.13.4) lib/mix/task.ex:397: anonymous fn/3 in Mix.Task.run_task/3
    (mix 1.13.4) lib/mix/cli.ex:84: Mix.CLI.run_task/2

Hi @NaN, do you have a module named MyApp.CustomRepo ?

defmodule MpApp.CustomRepo do
  use Ecto.Schema
  import Ecto.Changeset

  schema "table_name" do
    field :field_1, :string
    field :field_2, :map

    timestamps()
  end

  @doc false
  def changeset(custom_repo, attrs) do
    custom_repo
    |> cast(attrs, [:field_1, :field_2])
    |> validate_required([:field_1, :field_2])
  end
end

That is an ecto schema module, not a repo module. Are you retrofitting Ecto to an app that was created without it?

You just answered my question! Needed :

defmodule MpApp.CustomRepo do
  use Ecto.Repo,
    otp_app: :myApp,
    #adapter: Ecto.Adapters.MyXQL
    adapter: Ecto.Adapters.Postgres

  @doc """
  Dynamically loads the repository url from the
  DATABASE_URL environment variable.
  """
  def init(_, opts) do
    {:ok, Keyword.put(opts, :url, System.get_env("DATABASE_URL"))}
  end
end
1 Like