4

I have a Ruby script that is connection to a postgres database, runs some queries, and then closes/returns data to the user.

The script works fine, but if I give it a bad hostname the entire script just hangs, and I have to ctrl-Z out of it. I know that to get around this I need to look into the libpq backend for postgres, but I'm rather at a loss as to how to wrap it all up into my ruby script. I'm using Ruby 1.8 and the pg gem to handle the postgres stuff, call to open connection:

myConnection = PGconn.connect(host,port,pgOptions,pgTTY,name,user,password)

(options and tty are just blank strings)

Any help/tips/suggestions would be great!

AMIC MING
  • 6,306
  • 6
  • 46
  • 62
Will Bates
  • 81
  • 1
  • 4
  • It should time out after a minute or two. You're waiting on a TCP timeout. – derobert Jan 04 '13 at 20:14
  • I'd highly recommend looking into using [Sequel](http://sequel.rubyforge.org/) to manage your DB connections. It makes life much easier. Check out the [Cheatsheet](http://sequel.rubyforge.org/rdoc/files/doc/cheat_sheet_rdoc.html) for a taste of how nicely it does things. – the Tin Man Jan 04 '13 at 20:59

1 Answers1

2

There is a connect_timeout option so you could do as: USING STRING connection_string = "host=YOUR_HOST port=YOUR_PORT connect_timeout=YOUR_TIMEOUT PERIOD" PGconn.connect(connection_string)

PGconn.connect also offers a more rubyesque hash notation

:host => YOU_HOST, :port => YOUR_PORT, :connect_timeout => YOUR_TIMEOUT_PERIOD

Also you can wrap this in a begin rescue so that the rest of your code does not run if the connection timesout

Disclaimer: I have not actually tested this but it is part of the documentation for the pg gem

http://deveiate.org/code/pg/

engineersmnky
  • 25,495
  • 2
  • 36
  • 52