Can't connect to local MySQL server through socket. I want to connect to REMOTE db - ruby

This is my code.
I want to connect to remote database
require 'bundler/setup'
#require "mysql"
#require 'mysql2'
#require "active_record"
Bundler.require
#db_host = ENV["HOST"]
#db_user = ENV["USER"]
#db_pass = ENV['PASSWORD']
#db_name = "db_name"
require "active_record"
ActiveRecord::Base.establish_connection(
:adapter => 'mysql2',
:database => #db_name,
:username => #db_user,
:password => #db_pass,
:host => #db_host)
class ConversionRate < ActiveRecord::Base
end
class ConversionRateMonthly < ActiveRecord::Base
self.table_name = "conversion_rates_monthly"
end
class KdpReport < ActiveRecord::Base
end
class SalesCalculator
def run
p KdpReport.count
end
end
calculator = SalesCalculator.new
calculator.run
But I get this error:
/home/jonsdirewolf/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/mysql2-0.4.9/lib/mysql2/client.rb:89:in `connect': Can't connect to local MySQL server through socket
'/var/run/mysqld/mysqld.sock' (2) (Mysql2::Error)
It is strange but yesterday my code worked. what may be wrong? I want to connect to remote db, not local. And btw I use ruby without rails.

So, the problem is in empty environment var ENV["HOST"].
When host, passed to ActiveRecord is nil or equl to string localhost - AR will try to connect to db using socket.

Related

how do I read from a Database in ruby sinatra using active record

I want to read entrys from a Database using active_record and keep getting diffrent Errors like: Name error and can't find the database or it can't execute the query.
so my question here is how do i read from a database or execute SQL-queries and for example write the result into a variable?
require 'rubygems'
require 'sinatra'
require 'active_record'
require 'sqlite3'
ActiveRecord::Base.establish_connection(
:adapter => "sqlite3",
:database => "test.db"
)
class Article < ActiveRecord::Base
end
#ActiveRecord::Migration.create_table :users do |t|
# t.string :name
#end
class App < Sinatra::Application
end
get '/' do
output = users.select(:all)
f = File.open('name','a'); f.write(output); f.close
#puts User.first
To read the data from the users table, you'd simply do:
class User < ActiveRecord::Base
end
get '/' do
#users = User.all
puts "Grabbed #{#users.size} user(s) from database"
end

How to test Ruby OCI8 database services

Are there any tutorials or examples of testing Ruby OCI8 database services?
See "C:\RubyXXX\lib\ruby\gems\1.9.1\gems\ruby-oci8-2.1.0-x86-mingw32\test\test_oci8.rb" or wherever it is on your drive.
Lots of weblinks i'm not going to include, you can google them yourselve.
A very simple example
require 'oci8'
oci = OCI8.new('schema','password','db.server')
oci.exec('select * from table') do |record|
puts record.join(',')
end
Some unit testing for active-record and sqlite, you can adapt this for oci8
require 'active_record'
require "test/unit"
ActiveRecord::Base.establish_connection(
:adapter => "sqlite3",
:database => "sample.db"
)
class Album < ActiveRecord::Base;end
class Tester < Test::Unit::TestCase
def test_title
assert_equal('Sticky Fingers', Album.find_by_title('Sticky Fingers').title)
end
end

ruby active_record connection within a class

My problem is that I want to put my connection and SQL statements in site methods in my class, but when I put it in separate methods and call the methods from elsewhere it won't connect to my MySQL database. My code:
require 'active_record'
class Databaseoperation < ActiveRecord::Base
def initialize
$mysqlinfo = Hash[*File.read('/home/me/properties/mysql.property').split(/=|\n/)]
end
def mysqlConnect
self.establish_connection(:adapter => 'jdbcmysql', :database => 'mydb' , :host => 'localhost', :username => 'root', :password => 'root' )
end
def getSqlServer
$record = MysqlConnection.connection.select_all('SELECT * from Installation')
end
end
dbp = Databaseoperation.new
dbp.mysqlConnect
Error message:
ActiveRecord::ConnectionNotEstablished: ActiveRecord::ConnectionNotEstablished
retrieve_connection at /home/me/.rvm/gems/jruby-1.7.4/gems/activerecord-4.0.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:546
retrieve_connection at /home/me/.rvm/gems/jruby-1.7.4/gems/activerecord-4.0.0/lib/active_record/connection_handling.rb:79
connection at /home/me/.rvm/gems/jruby-1.7.4/gems/activerecord-4.0.0/lib/active_record/connection_handling.rb:53
columns at /home/me/.rvm/gems/jruby-1.7.4/gems/activerecord-4.0.0/lib/active_record/model_schema.rb:208
column_names at /home/me/.rvm/gems/jruby-1.7.4/gems/activerecord-4.0.0/lib/active_record/model_schema.rb:247
define_attribute_methods at /home/me/.rvm/gems/jruby-1.7.4/gems/activerecord-4.0.0/lib/active_record/attribute_methods.rb:29
synchronize at org/jruby/ext/thread/Mutex.java:149
define_attribute_methods at /home/me/.rvm/gems/jruby-1.7.4/gems/activerecord-4.0.0/lib/active_record/attribute_methods.rb:26
method_missing at /home/me/.rvm/gems/jruby-1.7.4/gems/activerecord-4.0.0/lib/active_record/attribute_methods.rb:123
mysqlConnect at ./databaseoperation.rb:12
(root) at ./databaseoperation.rb:23
If I don't put my statements inside methods in my class it connects to the database. But I really would like to be able to have connections and sql statements separated in methods for my class. How can I do this? Note that I'm using jruby-1.7.4.

Ldap gem throws no connection to server exception in Rails

Trying to establish a connection from a module in Rails and get no connection to server. I have tested the same code outside Rails and it works fine.
require 'rubygems'
require 'net-ldap'
module Foo
module Bar
class User
attr_reader :ldap_connection
def initialize
#ldap = Net::LDAP.new(:host => "<ip-number>", :port => 389)
#treebase = "ou=People, dc=foo, dc=bar"
username = "cn=Manager"
password = "password"
#ldap.auth username, password
begin
if #ldap.bind
#ldap_connection = true
else
#ldap_connection = false
end
rescue Net::LDAP::LdapError
#ldap_connection = false
end
end
end
end
end
Getting Net::LDAP::LdapError: no connection to server exception.
I found a solution/workaround for my problem with auto-loading in Rails. Added a new initializer to ensure that all Ruby files under lib/ get required:
Added config/initializers/require_files_in_lib.rb with this code
Dir[Rails.root + 'lib/**/*.rb'].each do |file|
require file
end
Read more about the workaround: Rails 3 library not loading until require

net-ssh and ActiveRecord 3: bringing it all together

I'm working on a small Ruby program that will connect to a remote MySQL Bugzilla database, perform a query of records, and email details of those records to a group on a daily basis.
So far, I've been able to SSH to the db server and execute a command using net-ssh. Here's an example:
require 'net/ssh'
Net::SSH.start("db.example.com", "sroach", :password => "secret") do |ssh|
result = ssh.exec!("ls -l")
puts result
end
That outputs just fine.
Using ActiveRecord 3.0.3, I wanted to test the establish_connection method so I established a connection to my local MySQL database and was able to execute commands using ActiveRecord. Example:
require 'active_record'
ActiveRecord::Base.establish_connection(
:adapter => "mysql2",
:host => "localhost",
:database => "list_tool_development",
:username => "my_username",
:password => "secretpassword"
)
class MailingList < ActiveRecord::Base
end
MailingList.first #=> Successfully retrieves first record from the table
So, where I'm having trouble is bringing it all together and applying it to my remote MySQL db. Here's my best try thus far:
require 'net/ssh'
Net::SSH.start("db.example.com", "sroach", :password => "secret") do |ssh|
ssh.forward.local(3307, "127.0.0.1", 3306)
ssh.loop { true }
end
But all that does is make my IRB session hang (which could be completely normal...don't know). Incase that hang was normal, I opened a new IRB session and tried to establish a connection to the remote database like so:
require 'active_record'
ActiveRecord::Base.establish_connection(
:adapter => "mysql2",
:host => "127.0.0.1",
:port => 3307,
:reconnect => false,
:database => "bugs",
:pool => 5,
:username => "my_username",
:password => "secret",
:socket => "/tmp/mysql.sock"
)
class Bug < ActiveRecord::Base #=> the table name in the "bugs" db is "bugs"
end #=> so I made the model singular
Bug.first #=> the IRB session hangs at this point
So, I have no idea what's going wrong or how to degub it. Any and all suggestions would be helpful.
I'm on Mac OSX. The db that I'm trying to connect to is on FreeBSD 7.0 and is MySQL version Ver 14.12 Distrib 5.0.67.
Rather than try to tunnel the ActiveRecord connection inside SSH, have you tried connecting directly from ActiveRecord to the DB server? That is the normal way to connect across a network and is directly supported by ActiveRecord.
Replace the host ID with the server host IP or DNS entry, the port can probably be allowed to default to the MySQL driver's default of 3306, and the socket isn't needed since the DB is on the remote host.
If the DB host isn't on the same network as yours, and you're crossing firewalls, you might need to have that port opened to allow the connection. If it is on the same network it should work without needing ssh at all.

Resources