Phantomwhale
Phantomwhale

Reputation: 1859

Checking the existence of a Postgres database from Ruby / Rails

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 ?

Upvotes: 0

Views: 103

Answers (1)

Jacob Brown
Jacob Brown

Reputation: 7561

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.

Upvotes: 1

Related Questions