I need to feed a SQL script to a Postgres database. I am creating a Process
instance that executes psql
with the script path as argument. The core of the code:
public static void main(final String[] args)
{
ProcessBuilder pb = new ProcessBuilder("psql", "-d base", "-U user", "-f path/new_schema.sql");
Map<String, String> env = pb.environment();
env.put("PGPASSWORD", "pass");
pb.redirectErrorStream(true);
try
{
Process p = pb.start();
InputStream stdout = p.getInputStream ();
BufferedReader reader = new BufferedReader (new InputStreamReader(stdout));
String line;
while ((line = reader.readLine ()) != null)
{
System.out.println ("Stdout: " + line);
}
}
catch (Exception ex)
{
System.out.println("Something went wrong: " + ex.getMessage());
}
}
This way authentication fails with this message:
psql: FATAL: Peer authentication failed for user "user"
Other users report the same error in other contexts, apparently Postgres 9.3 no longer uses the PGPASSWORD
environment variable.
Therefore I tried the alternative route using a .pgpass
file with these contents:
localhost:5432:*:user:pass
Then added a new environment variable before launching the Process
instance:
env.put("PGPASSFILE", "/home/user/.pgpass");
Still, I receive back the "authentication failed" message.
The .pgpass
file has the correct permissions (0600
) and is doing its job if I invoke psql
directly from the shell.
What am I missing?