-
-
Save hipertracker/5338d75e220b200dc92f6be3af65f5b5 to your computer and use it in GitHub Desktop.
Dynamic database configuration in Phoenix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[default] | |
DB_NAME=mydb | |
DB_PASSWORD=mypass | |
DB_USERNAME=myuser |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule MyApp.Repo do | |
use Ecto.Repo, | |
otp_app: :my_app, | |
adapter: Ecto.Adapters.Postgres | |
@doc """ | |
In the production mode you cannot run ConfigParser.parse_file(".env") or Mix.env() | |
So to detect the environment mode put a flag to config/prod.exs: | |
config :my_app, MyApp.Repo, env: :prod | |
""" | |
def init(_, config) do | |
if config[:env] == :prod do | |
{:ok, config} | |
else | |
{:ok, inject_env(config)} | |
end | |
end | |
defp inject_env(config) do | |
config | |
|> Enum.map(fn item -> | |
case ConfigParser.parse_file(".env") do | |
{:ok, %{"default" => conf}} -> modify_config(conf, item) | |
_ -> item | |
end | |
end) | |
end | |
defp modify_config(conf, item) do | |
case item do | |
{:username, nil} -> {:username, conf["DB_USERNAME"]} | |
{:password, nil} -> {:password, conf["DB_PASSWORD"]} | |
{:database, nil} -> {:database, conf["DB_NAME"]} | |
_ -> item | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment