cannot connect to Postgres (pg) database from my Ruby Script using gem "pg"(This is not rails, just pure ruby) - ruby

I downloaded the postgres.app for my Mac OSX machine. I have a rails app that has connected and used the postgres DB that came with the postgres app.
Now I am writing a pure Ruby test script (Not Rails, pure Ruby, not even Active Record) to try to connect to the postgres database instance. These are the steps I followed to set this up
1) ran this command on the terminal:
gem install pg -- --with-pg-config=/Applications/Postgres.app/Contents/MacOS/bin/pg_config
2) Added this code to the test script:
#!/usr/bin/env ruby
#encoding: utf-8
require "pg"
#conn = PG.connect(
:dbname => 'oData',
:user => 'am',
:password => '')
#conn.exec("CREATE TABLE programs (id serial NOT NULL, name character varying(255);");
I got this from this link
When I ran this script I get the following error:
/Users/am/.rvm/gems/ruby-2.0.0-p247/gems/pg-0.16.0/lib/pg.rb:38:in `initialize': could
not connect to server: No such file or directory (PG::ConnectionBad)
Is the server running locally and accepting
connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"?
My Debug efforts:
My postgres.app is up and running.
I looked at the pg gem [documentation][2] and my syntax seemed OK.
The location of my postgres DB is entered in my bash script like so
PATH="/Applications/Postgres.app/Contents/MacOS/bin:$PATH"
Not sure what to do next. Any help would be appreciated, Thanks.

are you sure postgres is listening on a socket? are you sure the username and password is right?
I would be inclined to try something like
require 'pg'
puts PG::Connection.ping(:dbname => 'oData',:user => 'am',:password => '')
puts "trying with tcp"
puts PG::Connection.ping(:dbname => 'oData',:user => 'am',:password => '', :port => 5432)

I used active record gem to make the connection work and it was fine

Settings to connect works for me.
But that code should look like
#conn.exec("CREATE TABLE programs (id serial NOT NULL, name
character(255))")

Related

Connecting to cloudant NoSQL database from ruby

I have trouble connecting to my cloudant NoSQL database hosted on bluemix with couchrest_model library.
I have similar code written in ruby which works just fine from my computer (running locally, no rails or sinatra):
require 'couchrest'
url = "https://blah-blah#url with credentials.com"
database_name = "testdb"
db = CouchRest.database!(url+"/"+database_name)
db.save_doc('_id':"dog",:name => 'MonthyPython', :date => Date.today)
doc = db.get('dog')
The code above successfully writes data to my database. However, when I tried to do similar thing with the newest 'couchrest_model' gem, I got the
/Users/userpruser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/net/http.rb:933:in `connect_nonblock': SSL_connect returned=1 errno=0 state=SSLv2/v3 read server hello A: unknown protocol (OpenSSL::SSL::SSLError)
I have viewed several pages, but with no luck. So what is the correct way to make it work with just ruby (no rails) or/and ruby+sinatra? I find this recipe http://recipes.sinatrarb.com/p/models/couchdb but I have no idea how to sed the evniroment variables and how to put it together.
Thanks for any help!
Did you try explicitly setting the port to 443 and the protocol to 'https'? See https://github.com/couchrest/couchrest_model#configuration
It looks like installing
gem install sinatra-config-file
and then requiring
require sinatra/config_file
solved my problem. Thanks to you all!

Ruby Sinatra/Postgres - can't connect to heroku database with PG.connect?

I am trying to get a site set up on Heroku using Sinatra and PostgreSQL. It worked locally (connecting to local database), but after pushing it to Heroku and changing my PG.connect to reflect that, I get an Internal Server Error the moment a page tries to access the database.
require 'uri'
require 'pg'
uri = URI.parse(ENV['DATABASE_URL'])
def db(uri)
begin
connection = PG.connect(uri.hostname, uri.port, nil, nil, uri.path[1..-1], uri.user, uri.password)
yield(connection)
ensure
connection.close
end
end
I am pretty sure these are parsing correctly, because ENV['DATABASE_URL'] displays the full postgres://user:password#host:port/database information that I'm expecting, and if I do the same in IRB uri.hostname, ui.port, etc all return what's expected .
This is my first time trying to get a site working on Heroku, so I am not even sure how to troubleshoot this. (And I googled for about all of yesterday.)
Results for heroku pg:
=== DATABASE_URL
Plan: Hobby-dev
Status: Available
Connections: 0/20
PG Version: 9.4.2
Created: 2015-05-30 19:24 UTC
Data Size: 17.7 MB
Tables: 5
Rows: 9320/10000 (In compliance, close to row limit)
Fork/Follow: Unsupported
Rollback: Unsupported
And all the tables show up when when I do heroku pg:psql <database> from the cli.
Some answers I've seen said to add database.yml to my root app directory, so:
production:
adapter: 'postgresql'
database: '<database>'
host: ENV['DATABASE_URL']
username: '<username>'
There's probably something simple I'm missing, but I haven't seen a complete guide for Sinatra/PSQL on Heroku - nothing that goes specifically into setting up and connecting to your database. (Everything seems Rails-related.)
In your database.yml file you need to specify the correct host for the host entry. You are passing what is stored in DATABASE_URL (something like postgres://user:password#host:port/database) but it should just be the host.
You will also need to specify a port if it isn't the default for PostgreSQL.
Edit: should also point out if you plan to store the host (or anything else - you definitely should for username and password) in an environment variable you'll need to wrap it, e.g. <%= ENV['HOST'] %>, not just ENV['HOST'] (i.e. how you have in the database.yml excerpt above)

Using SSPI with Ruby TinyTDS - possible?

After some anguish trying to connect to a SQLServer database with Ruby, I finally discovered TinyTDS and it's fantastic.
However, it requires a username and password to talk to the database. In C# tests in the past, we've used SSPI to supply this, so that any tester can pick up a script and run it and it'll use their Windows Authentication details.
I can't find a way to do this with TDS (beginning to suspect it's not possible with the current version) and hoping someone might prove me wrong, or have another suggestion?
Cheers.
Found the solution.
My install of tiny-tds was version 0.51.
The latest version has SSPI, and so to get that:
gem install tiny_tds --version ">= 0.6.0.rc1"
This comes with no need to specify a username/password and use SSPI by default.
So as an example:
require 'tiny_tds'
sql = "SELECT name from sys.databases"
client = TinyTds::Client.new(:dataserver => "myserver", :database => "mydatabase")
result = client.execute(sql)
results = result.each(:symbolize_keys => true, :as => :array, :cache_rows => true, :empty_sets => true) do |rowset| end
#THIS IS TO OUTPUT IT TO THE CONSOLE
for i in (0..result.fields.length)
printf("%14s", result.fields[i])
end
for j in (0...result.affected_rows)
puts ""
for i in (0...result.fields.length)
printf("%14s",results[j].at(i))
end
end
Will print out a list of the database names, using SSPI to access the database.

Ruby NET::SCP and custom ports

I'm trying to define a custom port for the ssh connection using Net::SCP, but without luck so far.
Here's an example how I'm trying to download a remote file from a server with a custom ssh port:
require "rubygems"
require 'net/scp'
Net::SCP.download!("www.server.com", "user", "/opt/platform/upload/projects/file.txt", "/tmp/bb.pdf",{:password => "mypassword",:port => 22202})
The error message I'm getting is:
Errno::ECONNREFUSED: Connection refused - connect(2)
There are no entries in the server logs regarding the ssh connection, so I assume that Net::SCP isn't using my custom port.
Any tips for me ?
Regards, Alex
Well, I've found the solution myself.
require "rubygems"
require "net/scp"
Net::SSH.start("www.myserver.com", "theuser", {:password => "whateverpwd",:port => 22212}) do |ssh|
ssh.scp.download! "/opt/platform/upload/projects/my.pdf", "/tmp/bb.pdf"
end
I also keep SSH on a non-standard port and use SCP like so:
Net::SCP.upload!( "foo.net", "user", the_file, the_file, :ssh => { :keys => #keys, :port => the_port } )
Works like a champ. I also use key-based authentication, hence the keys parameter getting passed along with the port.

Ruby Sinatra - connect to mongoDB on mongoHQ failed

This is just for my weekend project/study, I am very new to Sinatra and MongoDB.
I've installed the gems for mongoDB, such as: mongo, mongo_mapper and mongoid.
When I tried connecting to my database on MongoHQ from localhost, it encountered such an error:
Mongo::ConnectionFailure at /
failed to connect to any given host:port
* file: connection.rb
* location: connect
* line: 489
I found a similar thread on SO, but frankly speaking, I don't quite understand the answers...
Here is my code snippet:
require 'rubygems'
require 'sinatra'
require 'mongo'
require 'mongo_mapper'
get '/' do
MongoMapper.connection = Mongo::Connection.new('flame.mongohq.com', 27044)
MongoMapper.database = 'notes'
MongoMapper.database.authenticate('foo', 'bar')
erb :list
end
I took the above code from here, but it seems not working...
Which part is wrong? Is there another way to do this? In the end this test web app will be deployed onto heroku, so I hope the solution can work with both localhost and my heroku server.
Updated:
I just created a minimal code snippet to test the mongodb connection:
require 'rubygems'
require 'mongo'
db = Mongo::Connection.new("flame.mongohq.com", 27044).db("notes")
But still got the error, after timeout:
$ ruby mongodbtest.rb
/Library/Ruby/Gems/1.8/gems/mongo-1.0.8/lib/../lib/mongo/connection.rb:489:in
`connect': failed to connect to any given host:port (Mongo::ConnectionFailure)
from /Library/Ruby/Gems/1.8/gems/mongo-1.0.8/lib/../lib/mongo/connection.rb:137:in
`initialize'
from mongodbtest.rb:4:in `new'
from mongodbtest.rb:4
The hostname and port are according to mongoHQ documentation, so they must be right.
Thanks for the help in advance.
2nd Update:
I just tested the mongodb connection string using terminal:
mongo mongodb://flame.mongohq.com:27044/notes -u foo -p bar
Unfortunately this would get me an connection failed error, honestly, I don't know why...
I use
uri = URI.parse(ENV['MONGOHQ_URL'])
#mongo_connection = Mongo::Connection.from_uri( uri )
#mongo_db = #mongo_connection.db(uri.path.gsub(/^\//, ''))
#mongo_db.authenticate(uri.user, uri.password)
You can look up your mongo url using the heroku config --long command
Just gave this another try, this time, I was using the ip address taken from ping:
So, if I change :
db = Mongo::Connection.new('flame.mongohq.com', 27060).db("notes")
db.authenticate('fake', 'info')
To:
db = Mongo::Connection.new('184.73.224.5', 27060).db("notes")
db.authenticate('fake', 'info')
That will work...
I still don't understand why the domain name approach won't work, but at least I can finish this off :)

Resources