Occasionally, I uncover long-standing but overlooked PostgreSQL features. One such rarely-used feature is "pg_service.conf," a file you can create to configure services. It simplifies access by eliminating the need to specify host, port, and user details.
How does it work? Well, here's an example:
1 2 3 |
iMac:~ hs$ cat .pg_service.conf # a sample service |
[hansservice]
host=localhost port=5432 dbname=test user=hs password=abc
[paulservice]
host=192.168.0.45 port=5432 dbname=xyz user=paul password=cde
In this case two services have been defined. Note that PostgreSQL uses a standard .ini-file format. Inside a section you can use all connection parameters available in PostgreSQL (a full list can be found here: http://www.postgresql.org/docs/9.5/static/libpq-connect.html#LIBPQ-PARAMKEYWORDS).
The first important thing is that a service can be referenced by name. The way to do that is to set an environment variable:
1 |
iMac:~ hs$ export PGSERVICE=hansservice |
A connection can now be established without passing parameters to psql:
1 2 3 4 5 |
iMac:~ hs$ psql psql (9.5.0) Type 'help' for help. test=# |
Actually a pg_service.conf file is a pretty convenient thing to have. Maybe I should reconsider my behavior, and use this thing more often.
In case you need any assistance, please feel free to contact us.
In order to receive regular updates on important changes in PostgreSQL, subscribe to our newsletter, or follow us on Facebook or LinkedIn.
You need to load content from reCAPTCHA to submit the form. Please note that doing so will share data with third-party providers.
More InformationYou are currently viewing a placeholder content from Facebook. To access the actual content, click the button below. Please note that doing so will share data with third-party providers.
More InformationYou are currently viewing a placeholder content from X. To access the actual content, click the button below. Please note that doing so will share data with third-party providers.
More Information
Also, instead of
export PGSERVICE
you can swap services at psql invocation time in one line withPGSERVICE=myservice psql
Even better, I came up with adding this to my .bashrc:
pg() { PGSERVICE=$1 psql
}
you can also do "psql service=hansservice" because libpq accepts a connection string in the database name parameter.