0
votes

I have multipe Postgres repositories in my app. I use Ecto. All works.

Now I want to be able to change their details, such as login, password, host, dynamically. That is, I’d change login/password/hostname of a database via an html page, restart the connection with a database and it should continue working.

How can I do that?

I don’t want to use any third-party library.

1

1 Answers

1
votes

All you need is to start the respective GenServer to manage the connection. Assuming you have a repo config in repo_config variable, you might:

{:ok, pid} <- MyApp.Repo.start_link(repo_config)

This server should be started supervised, otherwise, it might crash and the connection will be lost forever. For supervising dynamically started GenServers we use DynamicSupervisor.


Also, you might use the same repo to manage different connections. In such a case, Ecto.Repo.put_dynamic_repo/1 and Ecto.Repo.get_dynamic_repo/0 are your friends.

current_pid = MyApp.Repo.get_dynamic_repo()
MyApp.Repo.put_dynamic_repo(repo_pid)
# deal with repo 
MyApp.Repo.put_dynamic_repo(current_pid)

In a vast majority of cases, the first approach (multiple repos) is preferred.