If you want to disconnect a database properly, there is the


#1

Hi,

We have worked on a problem of connection: Connect to
two databases with a single ActiveRecord::Base model
class within the same action
The main difficulty is how to disconnect the actual
connection properly and then let the ActiveRecord
establishes a new one.
The actual function “remove_connection” removes the
connection, but its doesn’t unbind the link between
rails and the database.
So we decide to add some new methodes in order to
remove all link between rails and the database.

First, we added a new methode to the adapter, we are
using postgresql, the following code is written for
postgresql_adapter.rb
if you are using another database, you have to rewrite
it. In postgresql_adapter.rb, add the follong code

  def disconnect
if (@connection != nil) then
	# methode "close" is exported by the postgres.so for

disconnect the database
@connection.close
@connection = nil # clear the connection
end
end

In connection_specification.rb, add the following code
at the end (in the “ActiveRecord::Base” class section)

def self.clear_connection(klass=self)
@@defined_connections.delete(klass) # remove
the connection
ac = active_connections # get the active
connection
ac.delete(klass) if ac.kind_of?(Hash) #
remove the connection
self.connection.disconnect # disconnect the
link with database, it call the newly added methode in
postgresql_adapter
@connection = nil # remove the connection
cached in the ActiveRecord::base class
end

For the tests, we have used the following code:

# first connection
GenTableAs.establish_connection(:adapter =>

“postgresql”,
:host => “1.2.3.4”,
:port => 5432,
:database => “db1”,
:username => “dbuser1”,
:password => “dbuser1”)

GenTableAs.set_table_name 'table_no_1'
	GenTableAs.reset_column_information()
	obj1 = GenTableAs.new
	@col1 = obj1.class.column_names()

obj1["colaa"] = 123
obj1["colab"] = "123"
obj1.save
obj1 = nil

GenTableAs.clear_connection	# here we disconnect the

connection

# connection to a new database
GenTableAs.establish_connection(:adapter =>

“postgresql”,
:host => “9.8.7.5”,
:port => 5432,
:database => “db2”,
:username => “dbuser2”,
:password => “dbuser2”)

GenTableAs.set_table_name "table_no_42"
	GenTableAs.reset_column_information()
	obj1 = GenTableAs.new
	@col2 = obj1.class.column_names()

obj1["col12"] = 456
obj1["col34"] = "789"
obj1.save
	obj1 = nil
GenTableAs.clear_connection	# here we disconnect

again the connection

It should give us the name of the columns of two
different tables of different database in @col1 and
@col2 and save the data to
tables.

So hope this will help who which to do the same thing,
(Actually, it takes us a few days to fully understand
the mecanism of the
database connection:))

If anyone has any comments about this, please
communicate with us:)!!!

Thanks you very much

Saiho


Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com