Can't drop postgres db when in test env

I got some test setup with sandbox db connection in my testcases. I configured text.exs to use a different db for the testcases and everything works as intended. The only thing which does not work properly is dropping the db before creating, migrating and seeding. The occurred error specifies that there is already an open connection to the db:

$ mix test
** (Mix) The database for MyApp.Repo couldn't be dropped: ERROR 55006 (object_in_use) database "test" is being accessed by other users
There is 1 other session using the database.

test.exs

config :my_app, MyApp.Repo,
  adapter: Ecto.Adapters.Postgres,
  username: System.get_env("POSTGRES_USER") || "postgres",
  password: System.get_env("POSTGRES_PASSWORD") || "postgres",
  database: System.get_env("POSTGRES_DB") || "test",
  hostname: System.get_env("POSTGRES_HOST") || "localhost",
  port: System.get_env("POSTGRES_PORT") || "5432",
  pool: Ecto.Adapters.SQL.Sandbox

mix.exs

...
defp aliases do
    [
      "ecto.setup": ["ecto.create", "ecto.load --skip-if-loaded", "ecto.migrate"],
      "ecto.seed": ["myapp.seed"],
      "ecto.setup.full": ["ecto.setup", "ecto.seed"],
      "ecto.reset": ["ecto.drop", "ecto.setup"],
      "ecto.migrate": ["ecto.migrate", "ecto.dump"],
      "ecto.rollback": ["ecto.rollback", "ecto.dump"],
      #"test.ecto": ["some calls", &function_call/1, "more calls"], #just an example how to call different tasks
      test: [&test_with_args/1],
      formatter: ["format mix.exs \"lib/**/*.{ex,exs}\" \"test/**/*.{ex,exs}\""]
    ]
  end

  defp test_with_args(args) do
    #https://github.com/elixir-lang/elixir/issues/2696

    Mix.Task.run "ecto.drop"
    Mix.Task.run "ecto.setup.full"
    Mix.Task.run "test", args
  end

  defp preferred_cli_env do
    [
      #when calling "mix test" elixir sets the ENV to :test automatically, if you call a different task you need the code below
      "test.ecto": :test
    ]
  end

In test_helper.exs i just do the recommended ExUnit.start() and Ecto.Adapters.SQL.Sandbox.mode(MyApp.Repo, :manual).

I don’t get where the connection is being accessed before and how can i fix that, so i can drop the db.

Do you have opened a mix phx.server in another terminal window at the same time or the mix test?

The error message is quite self-explanatory. If you have any other processes using the DB – iex, mix phx.server or even psql itself – then you are not allowed to drop it.

In your case, since it’s only one other client using the DB, I’d bet on you having a psql shell opened somewhere. (When it’s iex or mix phx.server using the DB, you’ll see another number, usually 10.)

Your assumptions were right… after checking the processes on the machine and the postgres-log, there was one open connection from a zombie process …
Thanks for your help, now everything works fine!