0

I found myself needing to check the existence of a Postgres database from Ruby, and ended up with the following (ugly) code:

def database_exists        
  `sudo su postgres -c 'psql -l | grep #{database_name} | wc -l'`.strip.to_i > 0
end

My concern is that not only is this not water-tight, but there must be a function already out there to do this sort of thing.

Can anyone let me know what functions exist in Ruby to do this cleanly ?

1 Answer 1

1

This is probably not as efficient as your code and requires the use of the pg library (https://github.com/ged/ruby-pg):

require 'pg'

def database_exists?(database_name)
  conn = PG.connect(:dbname => 'postgres')
  res = conn.exec("SELECT datname FROM pg_database").values.flatten
  res.include?(database_name)
end

You could probably make this more efficient by adding where datname = #{database_name} to the query and checking for an empty result set.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.