Postgrex.start_link runs in .exs but not in .ex

I’m new to Elixir and so likely this can be explained by something basic I have missed.

When I have the lines:

{:ok, pid} = Postgrex.start_link(hostname: “localhost”, username: “krp”,
password: “”, database: “bioi”)
in a .exs file it runs as expect. When I move it to a .ex file it throws the following error that I have not been able to explain. Thank you for any help.

== Compilation error in file lib/t.ex ==
** (MatchError) no match of right hand side value: {:error, {:noproc, {GenServer, :call, [DBConnection.Watcher, {:watch, DBConnection.ConnectionPool.Supervisor, {DBConnection.ConnectionPool.Pool, {#PID<0.152.0>, #Reference<0.529801177.2364145666.77097>, Postgrex.Protocol, [types: Postgrex.DefaultTypes, hostname: “localhost”, username: “krp”, password: “”, database: “bioi”]}}}, :infinity]}}}
lib/t.ex:2: (file)
(elixir) lib/kernel/parallel_compiler.ex:229: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/7

Applications aren’t started by default when compiling files.

  • .exs is Elixir script, meant to be interpreted rather than compiled
  • .ex is Elixir file, meant to be compiled to .beam files and then loaded with application
1 Like

Thank you hauleth. I am likely still missing some basic elixir points, the error occurs when I run “mix compile”

Without seeing your code, I am going to guess that you assume you have something along the lines of

defmodule Foo do
  {:ok, pid} = Postgrex.start_link(hostname: "localhost", username: "krp", password: "", database: "bioi")

  ...
end

Note how that code is not inside a function. Or you may even have it outside of the module definition. Either way, the code is being executed at compile time, which would not give you what you want and would be leading to this error.

2 Likes

Bingo!
Thank you Ankher: to be clear I have it right, code must be enclosed in a function to be compiled. Now seems obvious. Clearly though I needed it spelled out.

Thanks again to all

1 Like