I am building a RESTful API with Phoenix and PostgreSQL and run the Phoenix app and the database in separate docker containers using docker-compose. If I attach a shell to the Phoenix container and type mix ecto.reset
to reset the database, I get the following error:
** (Mix) The database for Home.Repo couldn't be dropped: ERROR 55006 (object_in_use):
database "home" is being accessed by other users
There are 10 other sessions using the database.
I already tried this:
REVOKE CONNECT ON DATABASE dbname FROM PUBLIC, username;
SELECT
pg_terminate_backend(pid)
FROM
pg_stat_activity
WHERE
pid <> pg_backend_pid()
AND datname = 'database_name';
What am I doing wrong?
You shouldn't stop only the cowboy webserver in this case, as it requires many phoenix dependencies to be up again, and most likely there will be a Supervision tree to restore the process if you find it and kill it yourself. So, as mentioned before, you should stop your whole phoenix server with Application.stop(:your_app) inside iex, and then do ecto.reset and start it again.
Although, you shouldn't need to use ecto reset within a running application, ecto.reset does the following: "ecto.drop", "ecto.create", "ecto.migrate"
. You should check if the drop is really necessary, as that is what's impossible to do in a running application that relies on database.
If you're resetting for testing purposes, for example, then you should also check Ecto.Sandbox, that sets up a copy database for each test: https://hexdocs.pm/ecto/Ecto.Adapters.SQL.Sandbox.html#content