module PsqlRunner extend self def check_connection(opt = {}) psql_path = find_psql unless psql_path result = "Can not find #{'psql'.bold} in your system\n" if RUBY_PLATFORM =~ /darwin/ result += "Please run 'brew install postgres' or download it from http://postgresapp.com" else result += "Please install postgresql package in your system" end result += "\nOr disable connection checking (--no-check-local and --no-check-remote)" return result end passwd = opt[:password] && opt[:password] == '' ? '' : "PGPASSWORD=#{opt[:password]}" psql_command = "#{passwd} #{psql_path} -h #{opt[:host]} -p #{opt[:port]} -U #{opt[:user]} #{opt[:database]} -c 'select now()'" if opt[:verbose] puts "EXEC #{psql_command}" end result = %x(#{psql_command} 2>&1) #unless result.include?('(1 row)') # puts result #end result.include?('(1 row)') ? true : result end def self.find_psql path = `which psql` if path != '' path = 'psql' elsif RUBY_PLATFORM =~ /darwin/ paths = Dir.glob('/Applications/Postgres.app/Contents/Versions/**/psql') path = paths.last if paths.size > 0 end path == '' ? nil : path end end