PostgreSQL – PSQL Connecting to Wrong Database

postgresqlpsql

I have noticed recently a weird (at least to me) behaviour of psql when trying to run psql -l. The essential steps to reproduce it are:

  1. Create a sample DB (I did it with docker and created a simple role with a password)
  2. Export environment variables that are used by psql

    PGPASSWORD=password
    PGDATABASE=database
    PGUSER=username
    
  3. Edit the pg_hba.conf. And instead of having the default for local I replaced it with. Of course don't forget about reloading the configuration.

    local   database          username                                  trust
    
  4. Running psql works as expected but running psql -l results in

    psql: FATAL:  no pg_hba.conf entry for host "[local]", user "username", database "database", SSL off
    

This seems to not take the environment variables into account when making a connection to the database.

Best Answer

This is expected behaviour.

The man page for psql says (emphasis mine):

-l

--list

List all available databases, then exit. Other non-connection options are ignored. This is similar to the meta-command \list.

When this option is used, psql will connect to the database postgres, unless a different database is named on the command line (option -d or non-option argument, possibly via a service entry, but not via an environment variable).