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 ?

4

1 回答 1

1

这可能不如您的代码高效,并且需要使用pg库(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

您可以通过添加where datname = #{database_name}到查询并检查空结果集来提高效率。

于 2013-08-29T22:37:16.947 回答