Lately, my prefered Postgres distribution of choice for OSX is Postgres.app.
Its very easy to download and install (just drag-n-drrop, like most other OSX Apps), no need to wait for it to compile, and it comes with a nice menubar icon for control.
In its default configuration it only listens on a port, but not on a unix
socket. The problem is, Rails recipes with postgres create a
config/database.yml
file that assumes a socket presence.
Of example:
✗ rails new test1 -d postgresql
create
create README.rdoc
...
Your bundle is complete!
Use `bundle show [gemname]` to see where a bundled gem is installed.
✗ cd test1
✗ rake db:create
could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"?
This problem was bothering me for a while as I tried to use rails_apps_composer to bootstrap new applications and it was failing on those database errors.
I didn’t want to mess with Postgres.app configs, as I suspected they’d be
overwriten on each version upgrade, so at first I tried to somehow trick it to
stop and let me replace the config/database.yml
file in time. The solution
turned out to be much simpler though.
The Rails Postgres driver recognizes standard Postgres environment variables,
one of which is PGHOST
. When set to localhost
Rails will go for the port
instead of the Unix socket, even if there is no host: localhost
setting in
the YAML file.
✗ PGHOST=localhost rake db:create
✗ _
So just add export PGHOST=localhost
to your shell start file, e.g. ~/.zshrc
and you are set.
Im actually went further with it, and now I have shell aliases to reset postgres env config, configure it for localhost, or read current application Heroku configs and pre-set Postgres environment for a direct access to Heroku db, but that is a topic for another blog post.