Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure Ecto at runtime?

Tags:

elixir

ecto

Following the setup instructions, I have the following Ecto configuration in my config/config.exs file :

config :my_app, MyApp.Repo,
  adapter: Ecto.Adapters.Postgres,
  url: "postgresql://postgres@localhost/myrepo",
  size: 20

If my understanding is correct, the config.exs is evaluated at compile-time.

Is there a way to do this configuration step at runtime ?

This is for an app which will be distributed as a compiled binary (via exrm). The end-user should be able to customize the database url and pool size via flags or environment variables, not by editing sys.config

like image 289
MrRuru Avatar asked Dec 19 '22 17:12

MrRuru


2 Answers

Loading from the system is possible by using {:system, "KEY" } e.g.:

config :my_app Repo
   url: {:system, "DATABASE_URL" },
   size: {:system, "DATABASE_POOL_SIZE" }

instead

config :my_app, Repo,
   url: "ecto://postgres:postgres@localhost/ecto_simple",
   size: 20

In this case you set up Ecto to use the system properties. Of course, a user has to configure it.

like image 87
Koziołek Avatar answered Dec 30 '22 07:12

Koziołek


Using {:system, "KEY"} has been deprecated in Ecto v3.

Instead, you are advised to define an init/2 callback function within your Repo module to set runtime config:

def init(_type, config) do
  config = Keyword.put(config, :url, System.get_env("DATABASE_URL"))

  {:ok, config}
end

Using a runtime init/2 function allows configuration to be read from more than just environment variables.

like image 20
Ben Smith Avatar answered Dec 30 '22 05:12

Ben Smith